Professional Documents
Culture Documents
C Book
C Book
INDEX
S.NO TOPIC PAGE NO
PREFACE 5
1.1 INTRODUCTION TO C PROGRAMMING 6
1.1.2 CHARACTERISTICS OF PROGRAMMING LANGUAGE
1.2 HISTORY OF ‘C’ LANGUAGE: 6
1.2.1 FEATURES OF ‘C’. 7
1.2.2 APPLICATION OF C PROGRAMMING/ USES OF C PROGRAMMING 7
GENERATIONS AND CLASSIFICATION OF PROGRAMMING 7
1.3
LANGUAGE
1.3.1 PROGRAMMING LANGUAGE CAN BE CLASSIFIED INTO 5 TYPES. 8
1.3.1.1 MACHINE LANGUAGE : 1ST GENERATION LANGUAGE(1GL) 8
1.3.1.2 ASSEMBLY LANGUAGE : 2ND GENERATION LANGUAGE(2GL) 8
1.3.1.3 HIGH LEVEL LANGUAGES : 3RD GENERATION LANGUAGE(3GL) 8
1.3.1.4 FOURTH GENERATION LANGUAGES : 4GL 8
1.3.1.5 FIFTH GENERATION LANGUAGES : 5GL 9
DEVELOPING A PROGRAM IN "C": EXECUTION PROCESS 9
1.4
OF C PROGRAM
1.4.1 IMPORTANT POINTS 11
1.4.2 DIFFERENCE BETWEEN COMPILER AND INTERPRETER 12
1.5 COMMENTS IN C PROGRAMMING 12
1.6 ALGORITHMS AND FLOWCHART 13
1.6.1 ALGORITHMS 14
1.6.2 FLOWCHART 14
PROGRAMMING EXPLANATION / UNDERSTANDING THE 16
1.7
PROGRAM
1.8 STRUCTURE OF C PROGRAM: 17
1.9 PROGRAMMING RULES 19
1.10 CHARACTER SET : 20
1.11 C TOKENS 20
1.11.1 IDENTIFIERS 21
1.11.2 KEYWORDS 21
1.11.3 CONSTANTS 22
1.11.4 STRING CONSTANT 23
1.11.5 VARIABLES 23
1.11.6 DATA TYPES: 24
2
1.11.7 OPERATORS 26
1.12 EXPRESSIONS 33
1.12.1 OPERATOR PRECEDENCE AND ASSOCIATIVITY IN C 34
1.13 TYPE CONVERSION: 36
1.13.1 1. IMPLICIT TYPE CONVERSION 37
1.13.2 2. EXPLICIT TYPE CONVERSION 37
1.14 C – LIBRARY FUNCTIONS 38
1.15 C PREPROCESSOR DIRECTIVES: 39
1.16 TYPES OF ERRORS ; 39
ESCAPE CHARACTERS OR BACKSLASH CHARACTERS OR 42
1.17
ESCAPE SEQUENCES :
2.1.1 FORMATTED INPUT/OUTPUT FUNCTIONS 42
2.1.2 UNFORMATTED INPUT/OUTPUT FUNCTIONS 43
2.2 CONTROL STATEMENTS IN C LANGUAGE 43
2.2.1 DECISION STATEMENTS / SELECTION STATEMENTS 44
2.2.2 IF STATEMENT IN C: 44
2.2.3 SWITCH STATEMENT IN C 48
LOOPING STATEMENTS/ REPETITION STATEMENTS / 49
2.3
LOOPS
2.3.1 . WHILE LOOP: 50
2.3.2 FOR LOOP: 50
2.3.3 DO-WHILE LOOP: 51
2.4 BREAK AND CONTINUE STATEMENTS: 52
2.5 GOTO STATEMENT: 53
2.6 NESTING OF LOOPS 53
2.7 FUNCTIONS 56
2.7.2 ADVANTAGES OF USER DEFINED FUNCTIONS : 56
THE FUNCTIONS CAN BE CLASSIFIED INTO TWO CATEGORIES. OR 56
2.7.3
TYPES OF FUNCTIONS
2.7.3.1 BUILT-IN FUNCTIONS (OR) LIBRARY FUNCTIONS : 56
2.7.3.2 USER DEFINED FUNCTIONS : 56
2.7.4 ELEMENTS OF USER-DEFINED FUNCTIONS : 57
2.7.5 PARAMETERS : 59
2.7.6 FUNCTION VARIABLES : 60
2.7.7 CATEGORY OF FUNCTIONS / TYPES OF USER DEFINED FUNCTIONS : 61
2.8 RECURSION 64
2.8.1 RECURSION LIMITATIONS : 65
2.8.2 ADVANTAGES OF RECURSION 65
3
2.9 ARRAYS 65
2.9.1 DECLARATION OF AN ARRAY / DEFINING AN ARRAY 66
2.9.2 INITIALIZING ARRAYS : 66
2.9.3 ONE – DIMENSIONAL ARRAYS:- 67
2.9.4 TWO - DIMENSIONAL ARRAYS:- 68
2.9.5 TWO DIMENSIONAL ARRAYS OR MULTI DIMMESIONAL ARRAY 69
3.1 STRINGS: OR CHARACTER ARRAYS 71
3.1.1 DECLARATION OF STRINGS:- 71
3.1.2 INITIALIZATION OF STRINGS 71
3.1.3 READING STRINGS: 71
3.1.4 WRITING OR PRINTING OF STRINGS TO SCREEN:- 72
STRING HANDLING FUNCTIONS:- OR STRING 72
3.2
MANIPULATION FUNCTIONS OR STRING.H FUNCTIONS
3.3 POINTERS AND STRINGS: OR CHARACTER POINTER 75
3.4 ARRAYS OF STRINGS: 76
3.5 STRING INPUT OUTPUT FUNCTIONS: 76
UNFORMATED I/O FUNCTIONS 80
3.6
BUILT IN FUNCTIONS :
3.7 MATH.H 80
3.8 DATE FUNCTIONS IN C 81
3.9 POINTERS: 82
3.9.1 INTRODUCTION 82
3.9.2 USES OF POINTERS : 82
DECLARATION AND INITIALIZATION OF POINTER 82
3.10
VARIABLES:-
3.11 POINTER EXPRESSIONS OR POINTER ARITHMETIC 84
3.12 POINTER TO POINTER 85
3.13 POINTERS TO FUNCTIONS: 86
VOID POINTER ( OR ) GENERAL PURPOSE POINTER (OR) 88
3.14
GENERIC POINTER OR POINTERS TO VOID
MEMORY ALLOCATION FUNCTIONS OR DYNAMIC 89
3.15
MEMORY ALLOCATIONS (DMA)
4.0 USER DEFINED DATA TYPES STRUCTURES & FILES 93
4.1 USER DEFINED DATA TYPES : 93
4.1.1 DEFINITION OF STRUCTURES : 94
4.1.2 DECLARATION OF STRUCTURES : 95
4.1.3 INITILIZATION OF STRUCTURES : 95
4
PREFACE
This book is organized which includes theory as well as programs for each topic.
I have put my best efforts in preparing this book, but if any errors or mistakes and
if any topic has been skipped out, please let me know your suggestions through email
provided below.
What is C?
Why do we use C?
a) The language must allow the programmer to write simple, clear and concise
programs.
b) The language must be simple to use so that a programmer can learn it without any
explicit training.
c) The language must be platform independent. That is, the program developed using
the programming language can run on any computer system.
d) The Graphical User Interface (GUI) of the language must be attractive, user-
friendly, and self-explanatory.
e) The programs developed in the language must make efficient use of memory as
well as other computer resources.
The language which uses all instructions and data should be written using binary codes 1
and 0 . The binary code is called machine code or machine language. Computers do not
understand English, Hindi and Tamil. They respond only to machine language. each
computer has its own machine language.
High level languages are like C , C++ are easier to use, and more portable across
platforms , as compared to low-level language.
Examples of high level languages: C, C++, Java etc
Following are the applications and software used to create and execute C programs.
Turbo C
Turbo C++
GNU C
Code Blocks
Net Beans
To create and execute C programs in the Windows Operating System, we need to install
Turbo C software.
Below are the steps to be followed for any C program to create and get the output. This is
common to all C program and there is no exception whether its a very small C program
or very large C program.
1. Create
2. Compile
3. Execute or Run
4. Get the Output
Step 1: Creating a Source Code
10
Whenever we press Alt + F9, the source file is going to be submitted to the Compiler. On
receiving a source file, the compiler first checks for the Errors. If there are any Errors
then compiler returns List of Errors, if there are no errors then the source code is
converted into object code and stores it as a file with .obj extension. Then the object code
is given to the Linker. The Linker combines both the object code and specified header file
code and generates an Executable file with a .exe extension.
We use a shortcut key Ctrl + F9 to run a C program. Whenever we press Ctrl + F9, the
.exe file is submitted to the CPU. On receiving .exe file, CPU performs the task
according to the instruction written in the file. The result generated from the execution is
placed in a window called User Screen.
Type the program in C editor and save with .c extension (Press F2 to save).
Press Alt + F9 to compile the program.
If there are errors, correct the errors and recompile the program.
If there are no errors, then press Ctrl + F9 to execute/run the program.
Press Alt + F5 to open User Screen and check the result.
Editor
This program is used for Writing the Source Code, the first thing that any
programmer writing a program in any language would be doing.
Pre-Processer
There are certain special instructions within the source code identified by the #
symbol that are carried on by a special program called a preprocessor.
Linker: Linker is a computer program that links and merges various object files/
header files together in order to make an executable file. All these files might have
been compiled by separate assembler.
It calculates the size of a program (instructions and data) and create memory space
for it. It initializes various registers to initiate execution.
COMPILER INTERPRETER
A Compiler is used to compile an entire An interpreter is used to translate each
program and an executable program is line of the program code immediately as
generated through the object program it is entered
The executable program is stored in a The executable program is generated in
disk for future use or to run it in another RAM and the interpreter is required for
computer each run of the program
The compiled programs run faster The Interpreted programs run slower
Most of the Languages use compiler A very few languages use interpreters.
When we are used the comments, then that specific part will be ignored by compiler.
Ex: //---------
Multi-line comments
Multi-line comments are used to add a detailed description about the code. It begins
with /* character and ends with */. Characters between /* */ are treated as comments.
Multi-line comments can span upto multiple lines. In addition, you can use multi-line
comments for both single as well as multiple line commenting.
ex: /* --------
--------
-------- */
1.6.1 Algorithms :
Characteristics of Algorithms :
Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 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
2. Write an algorithm to find the largest among three different numbers entered by user.
Step 1: Start
Step 2: Declare variables a,b and c.
Step 3: Read variables a,b and c.
Step 4: If a>b
If a>c
Display a is the largest number.
Else
Display c is the largest number.
Else
If b>c
Display b is the largest number.
Else
Display c is the greatest number.
Step 5: Stop
1.6.2 Flowchart:
Flowchart Symbols
15
Let us look at a simple code that would print the words "Hello World" −
#include <stdio.h>
int main()
{
/* my first program in C */
printf("Hello, World! \n");
return 0; }
The first line of the program #include <stdio.h> is a preprocessor command, which
tells a C compiler to include stdio.h file before going to actual compilation.
17
The next line int main() is the main function where the program execution begins.
The next line /*...*/ will be ignored by the compiler and it has been put to add
additional comments in the program. So such lines are called comments in the
program.
The next line printf(...) is another function available in C which causes the message
"Hello, World!" to be displayed on the screen.
The next line return 0; terminates the main() function and returns the value 0.
Every ‘C’ program may contain one or more sections given below.
1 : Documentation section : It consist of a set of comment lines giving the name of the
program, the author and other details etc. Documentation section is a optional section.
18
Comments : means are very helpful in identifying the program features and underlaying
logic of the program. The lines begins with ‘/*’ and ending with ‘*/’ are known as
comment lines. These are not executable, the compiler is ignored any thing in between /*
and */.
// for single line comment
Ex : #define PI 3.14
4 : Global Declaration : There are some variables that are used in more than one
function. Such variables are called global variables and are declared in the global
declaration section that is outside of all the functions. This section also declares all the
user-defined functions.
5 : main() function : Every C program must have one main(0 function. This section
contains two parts.
a : Declaration part : This part is used to declare all the variables that are used in
the executable part of the program and these are called local variables.
b : Executable part : It contains atleast one valid ‘C’ statement. The execution of
a program begins with opening brace ‘{‘ and ends with closing brace ‘}’. The
closing brace of the main() function is the logical end of the program.
All the statements in the program ends with a semicolon except conditional and
control statements.
6 : Sub Program section : This contains all the user defined functions that are called in
the main() function. User defined functions are generally placed immediately after the
main() function.
1. All statements in ‘C’ program should be written in lower case letters. Upper case
letters are only used for symbolic constants.
2. The program statement can write anywhere between the two braces following the
declaration part.
3. The user can also write one or more statements in one line separating them with a
semicolon.
4. Blank spaces are not used while declaring a variable, keyword, constant, and
function.
5. every statement in c language should end with semi colon
6. every c program should have one main function.
Symbolic Constants : The constants which will be used no of places in a program can be
defined using define statement.
Ex : #define PI 3.142
#define HUNDRED 100
The C character set consist of upper and lowel case alphabets, digits, special characters
and white spaces. The alphabets and digits are together called the alphanumeric
characters.
1. Alphabets :
ABCDEF...................XYZ
abcdef......................xyz
2. Digits : 0 1 2 3 4 5 6 7 8 9
3. Special characers :
1.11 C TOKENS :
The smallest individual units are known as tokens. C has six types of tokens.
1 : Identifiers
2 : Keywords
3 : Constants
4 : Strings
5 : Variables
6: Data types
7 : Operators.
21
1.11.1: Identifiers : Identifiers refer to the names of variables, functions and arrays.
These are user-defined names is called Identifiers.
Rules :
1 : Identifier names must be a sequence of letters and digits.
2 : The first character must be a letter/character or may begin with underscore ( _ ).
3 : The underscore character ( ‘ _ ‘) is considered a letter.
4 : Both upper/lower cases are permitted although uppercase character is not equilent
to corresponding lowercase character.
5 : ‘C’ compiler recognizes only the first 31 characters of an identifiers.
6 : No space and special symbols are allowed between the identifier.
7 : Identifier cannot be a keyword.
Ex : Valid Invalid
STDNAME Return
SUB $stay
TOT_MARKS 1RECORD
_TEMP STD NAME.
Y2K
1.11.2: Keywords : All keywords have fixed that means cannot be changed. Keywords
serve as basic building blocks for program statements. All keywords must be written in
lowercase.The ‘C’ keywords are listed below.
1.11.3: Constants : Constants refer to fixed values that do not change during the
execution of a program.
22
1 : Decimal Integer
2 : Octal
3 : Hexadecimal
Ex : 777 -77
Octal : An integer constants with base 8 is called octal. These rules are :
Ex : 15.25
a) \n newline
b) \r carriage return
c) \t tab
d) \v vertical tab
e) \b backspace
f) \f form feed (page feed)
g) \a alert (beep)
h) \’ single quote(‘)
i) \” double quote(“)
j) \? Question mark (?)
k) \\ backslash (\)
1.11.5. Variables : A variable is a memory location used to store any date value.
Variable is also called as an identifier
Declaration of Variables :
The declaration of variables must be done before they are used in the program. The
general format for declaring a variable.
Ex : int x,y,z;
float a,b;
char m,n;
values can be assigned to variables using the assignment operator (=). The general
format statement is :
Ex : x=100;
1.11.6.Data Types:
Datatype is used to specify what type of data can be stores in a variable. C Data Types
are used to:
Arrays : Arrays are sequences of data items having homogeneous values. They
have adjacent memory locations to store values.
Pointers : These are powerful C features which are used to access the memory and deal
with their addresses.
Union: These allow storing various data types in the same memory location.
Programmers can define a union with different members, but only a single member can
contain a value at a given time.
Enum: Enumeration is a special data type that consists of integral constants, and
each of them is assigned with a specific name. "enum" keyword is used to define the
enumerated data type.
Operators are used in C language program to operate on data and variables. C has a rich
set of operators which can be classified as
Types of Operators :
1) Arithmetic Operators.
2) Relational Operators.
3) Logical Operators.
4) Assignment Operators.
27
5) Bitwise Operators.
6). Unary Operators. Increment and decrement
7) Conditional Operators. Terinary
8) Special Operators.
#include <stdio.h>
void main()
{
int a = 15, b = 5, result;
clrscr();
result = (a < b);
printf("result is %d \n", result);
result = (a >b);
printf("result is %d \n", result);
result = (a >=b) ;
printf("result is %d \n", result);
result = (a <=b) ;
printf("result is %d \n", result);
result = (a==b) ;
printf("result is %d \n", result);
result = (a != b);
printf("result is %d \n", result);
getch();
}
29
3) Logical Operators :
These operators are used to combine the results of two or more conditions. ‘C’ has
the following logical operators. The symbols are :
#include <stdio.h>
Void main()
{
int a = 15, b = 5, c = 10, result;
result = (a < b) && (c > b);
printf("result is %d \n", result);
result = (a >b) && (c < b);
printf("result is %d \n", result);
result = (a >b) || (c < b);
printf("result is %d \n", result);
result = (a != b) || (c < b);
printf("result is %d \n", result);
result = !(a != b);
printf("result is %d \n", result);
}
4 ) Assignment Operator :
Assignment operators are used to assign a value (or) an expression (or) a value of a
variable to another variable.
Ex : x=10;
y=20;
#include <stdio.h>
void main()
{
int a = 5, c; c %= a; // c = c%a
c = a; printf("c = %d \n", c);
printf("c = %d \n", c); }
c += a; // c = c+a
printf("c = %d \n", c); Output
c -= a; // c = c-a c=5
printf("c = %d \n", c); c = 10
c *= a; // c = c*a c=5
printf("c = %d \n", c); c = 25
c /= a; // c = c/a c=5
printf("c = %d \n", c); c=0
The operator ++ adds 1 to the operand and – subtracts 1 from the operand. These
operators in two forms : prefix (++x) and postfix(x++).
Operator Meaning
++x Pre increment
- -x Pre
decrement
x++ Post
increment
x-- Post
decrement
Where
6 ) Conditional (or) Ternary Operator : Conditional operator checks the condition and
executes the statement depending of the condition. Conditional operator consist of two
symbols.
#include<stdio.h>
int main()
{
int num;
printf("Enter the Number : ");
scanf("%d",&num);
(num%2==0)?printf("Even"):printf("Odd");
}
7 ) Special Operators :
i. Comma Operator :The comma operator is used to separate the statement elements
such as variables, constants or expressions
Ex: int a,b
ii) Sizeof Operator : The sizeof() is a unary operator, that returns the length in bytes o
the specified variable, and it is very useful to find the bytes occupied by the specified
variable in the memory.
Syntax : sizeof(variable-name);
int a;
Ex : sizeof(a); //OUTPUT-----2bytes
#include<stdio.h>
33
int main() {
printf("%d", sizeof(int));
printf("%d", sizeof(char));
printf("%d", sizeof(float));
return 0;
}
8) Bitwise Operators :
Bitwise operator s are used to manipulate the data at bit level. It operates on integers
only. It may not be applied to float.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Shift left
>> Shift right
~ One’s complement.
Example 8 : Bitwise :
#include <stdio.h>
Void main()
{
Int a,b,c;
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
c = a & b; /* 12 = 0000 1100 */
printf("Value of c is %d\n", c ); c = a >> 2; /* 15 = 0000 1111 */
c = a | b; /* 61 = 0011 1101 */ printf("Value of c is %d\n", c );
printf("Value of c is %d\n", c ); }
c = a ^ b; /* 49 = 0011 0001 */
printf("Value of c is %d\n", c );
c = ~a; /*-61 = 1100 0011 */
printf("Value of c is %d\n", c ); Output:
c = a << 2; /* 240 = 1111 0000 */
printf("Value of c is %d\n", c ); Value of c is 12
34
1.12 EXPRESSIONS:
In C programming language, expressions are divided into THREE types. They are as
follows...
Infix Expression
The expression in which operator is used between operands is called as infix expression.
The infix expression has the following general structure...
Postfix Expression
The expression in which operator is used after operands is called as postfix expression.
The postfix expression has the following general structure...
Prefix Expression
The expression in which operator is used before operands is called as prefix expression.
The prefix expression has the following general structure...
Operator associativity is used to determine the order of operators with equal precedence
evaluated in an expression. In c programming language, when an expression contains
multiple operators with equal precedence, we use associativity to determine the order of
evaluation of those operators.
In the above table, the operator precedence decrease from top to bottom and increase
from bottom to top.
Expression Evaluation in C
10 + 4 * 3 / 2
In the above expression there are three operators +, * and /. Among these three operators,
both multiplication and division have same higher precedence and addition has lower
precedence. So, according to the operator precedence both multiplication and division are
evaluated first and then addition is evaluated. As multiplication and division have same
precedence they are evaluated based on the associativity. Here, the associativity of
multiplication and division is left to right. So, multiplication is performed first, then
37
division and finally addition. So, the above expression is evaluated in the order of * / and
+. It is evaluated as follows...
4 * 3 ====> 12
12 / 2 ===> 6
10 + 6 ===> 16
The expression is evaluated to 16.
This type of conversion is usually performed by the compiler when necessary without
any commands by the user. Thus it is also called "Automatic Type Conversion".
The type conversion performed by the programmer by posing the data type of the
expression of specific type is known as explicit type conversion. The explicit type
conversion is also known as type casting.
#include <stdio.h>
#include <conio.h> printf("Result = %d\n", result);
void main() getch();
{ }
float x = 24.5, y = 7.2;
int result; Output
clrscr();
result = (int) x / (int) y; Result = 3
In the above code (int) x converts the value 24.5 into 24 and (int) y converts the value
7.2 into 7 so, we get 24/7 i.e.,
3 as result because result is of type int and hence the decimal part is truncated
Commands used in preprocessor are called preprocessor directives and they begin
with “#” symbol.
Below is the list of preprocessor directives that C programming language offers.
Macro
Header file inclusion
Conditional
40
Preprocessor Description
Syntax: #define
Macro This macro defines constant value and can be any of the basic
data types.
Syntax: #include <file_name>
Headerfile
The source code of the file “file_name” is included in the
inclusion
main program at the specified place.
Syntax: #ifdef, #endif, #if, #else, #ifndef
Conditional
Set of commands are included or excluded in source program
compilation
before compilation with respect to the condition.
Syntax Error
Run-Time Error
Linker Error
Logical Error
Semantic Error
Runtime error
41
This kind of errors are occurred, when the program is executing. As this is not
compilation error, so the compilation will be successfully done. We can check this error
if we try to divide a number with 0.
Example
#include<stdio.h>
main() {
int x = 52;
int y = 0;
printf("Div : %f", x/y);
}
Output
Program crashes during runtime. since division is not possible
Linker error
This kind of errors are occurred, when the program is compiled successfully, and trying
to link the different object file with the main object file. When this error is occurred, the
executable is not generated, For example some wrong function prototyping, incorrect
header file etc. If the main() is written as Main(), this will generate linked error.
Example
#include<stdio.h>
main() {
int x = 52;
int y = 0;
printf("Div : %f", x/y);
}
Output : C:\crossdev\src\mingw-w64-v3-git\mingw-w64-crt\crt\crt0_c.cundefined
reference to `WinMain'
Logical error
Sometimes, we may not get the desired output. If the syntax and other things are correct,
then also, we may not get correct output due to some logical issues. These are called the
logical error. Sometimes, we put a semicolon after a loop, that is syntactically correct, but
will create one blank loop. In that case, it will show desired output.
Example
#include<stdio.h>
main() {
int i;
for(i = 0; i<5; i++);
{
printf("Hello World");
42
}
}
Output
Here we want the line will be printed five times. But only one time it will be printed for
the block of code.
Semantic error
This kind of error occurs when it is syntactically correct but has no meaning. This is like
grammatical mistakes. If some expression is given at the left side of assignment operator,
this may generate semantic error.
Example
#include<stdio.h>
main() {
int x, y, z;
x = 10;
y = 20;
x + y = z;
}
Output
[Error] lvalue required as left operand of assignment
i) \” double quote(“)
j) \? Question mark (?)
k) \\ backslash (\)
Functions Description
This function is used to read one or multiple inputs
scanf()
from the user at the console.
This function is used to display one or
printf() multiple values in the output to the user at the
console.
This function is used to read the characters from a
sscanf()
string and stores them in variables.
This function is used to read the values stored in
sprintf() different variables and store these values in a
character array.
Unformatted console input/output functions are used to read a single input from the user
at console and it also allows us to display the value in the output to the user at the
console.
44
Functions Description
Reads a single character from the user at the
getch()
console, without echoing it.
Reads a single character from the user at the console, and
getche()
echoing it.
Reads a single character from the user at the console, and
getchar() echoing it, but needs an Enter key to be pressed at the
end.
Decision making statements are the statements that are used to verify a given
condition and decides whether a block of statements gets executed or not based on the
condition result.
In c programming language, there are two decision making statements they are as
follows...
1. if statement
2. switch statement
2.2.2 if statement in c:
1) Simple if statement
2) if - else statement
3) Nested if statement
46
Simple if statement
Simple if statement is used to verify the given condition and executes the block of
statements based on the condition result. The simple if statement evaluates specified
condition. If it is TRUE, it executes the next statement or block of statements. If the
condition is FALSE, it skips the execution of the next statement or block of statements.
The general syntax and execution flow of the simple if statement is as follows...
Simple if statement is used when we have only one option that is executed or skipped
based on a condition.
#include <stdio.h>
#include<conio.h>
void main()
{
int n ; clrscr() ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n> 0 ) }
printf("Given number is natural
number ") ; O/P: Enter any integer number: 4
getch(); Given number is natural number
47
if - else statement
The if - else statement is used to verify the given condition and executes only one out of
the two blocks of statements based on the condition result. The if-else statement evaluates
the specified condition. If it is TRUE, it executes a block of statements (True block). If
the condition is FALSE, it executes another block of statements (False block). The
general syntax and execution flow of the if-else statement is as follows...
The if-else statement is used when we have two options and only one option has to be
executed based on a condition result (TRUE or FALSE).
#include <stdio.h>
#include<conio.h>
void main(){
int year ;
clrscr() ;
printf("Enter year: ") ;
scanf("%d", &year) ;
if ( year%4 == 0 ) }
printf("Given year is leap year\n") ; Output :
else
printf("Given year is not leap Enter year: 2017
year\n") ; Given year is not leap year
48
Nested if statement
Like the name indicate, nested else if contains if statement inside an if statement. If we
want to check a condition even a condition is hold, then we use nested if.
#include <stdio.h> Output :
#include <stdlib.h>
int main()
{ Largest is 30
int n1 = 30,n2 = 20 ,n3 = 10; Here n1(30) is greater than n2(20), so
if(n1 > n2) again check with the value of n3(10).
{ Then decided a decision( printf("Largest
if(n1>n3) is %d",n1); )
{
printf("Largest is %d",n1);
}
}
}
49
Using switch statement, one can select only one option from more number of options
very easily. In switch statement, we provide a value that is to be compared with a value
associated with each option. Whenever the given value matches with the value associated
with an option, the execution starts from that option. In switch statement every option is
defined as a case.
50
The switch statement contains one or more number of cases and each case has a value
associated with it. At first switch statement compares the first case value with the
switchValue, if it gets matched the execution starts from the first case. If it doesn't match
the switch statement compares the second case value with the switchValue and if it is
matched the execution starts from the second case. This process continues until it finds a
match. If no case value matches with the switchValue specified in the switch statement,
then a special case called default is executed.
When a case value matches with the switchValue, the execution starts from that particular
case. This execution flow continues with next case statements also. To avoid this, we use
"break" statement at the end of each case. That means the break statement is used to
terminate the switch statement. However it is optional.
Loops provide a way to repeat a set of statements and control how many times they are
repeated.
Both while and for statements are called as entry-controlled loops because they evaluate
the expression and based on the value of the expression they transfer the control of the
program to a particular set of statements.
Do-while is an example of exit-controlled loop as the body of the loop will be executed
once and then the expression is evaluated.
In above syntax, the condition is checked first. If it is true, then the program control flow
goes inside the loop and executes the block of statements associated with it. At the end of
loop increment or decrement is done to change in variable value. This process continues
until test condition satisfies
For loop example program:
#include <stdio.h>
Void main()
{
int x;
for ( x = 0; x < =10; x++ )
{
printf( "%d\n", x );
}
getch();
}
o/p: 0 1 2 3 4 5 6 7 8 9 10
do
{
statements;
(increment/decrement);
} while (expression/condition);
#include<stdio.h> if(i==5)
#include<conio.h> break;
void main() { }
int i;clrscr(); getch();
for(i=1; i<=100; i++) }
{ o/p: 1 2 3 4 5
printf("%d\t,i");
CONTINUE
Continue is a keyword . the continue statement is used to skip over the rest of the
current iteration. After continue statement, the control returns to the top of the loop.
#include<stdio.h> #include<conio.h>
void main() {
int i; clrscr();
for(i=1; i<=10; i++)
{
if(i==5)
continue;
printf("%d",i);
}
getch();
}
o/p: 1 2 3 4 6 7 8 9 10
Example program for Continue :
2.5 Goto statement:
A goto statement is used to branch (transfer control) to another location in a program.
Syntax:
55
The label can be any valid identifier name and it should be included in the program
followed by a colon.
Example program
Output :
Hello World
Hope you are fine
Note : Break, continue ad goto statements are also called as jumping statements.
Syntax :
outer_loop
{
inner_loop
{
// Inner loop statement/s
}
{
// statements
// statements
}
while(condition)
{
// Inner loop statements
}
// statements
}
Nested do...while loop
do
{
// statements
do
{
// Inner loop statements
}
while(condition);
// statements
}
Example:
Print number 1 to 10, 5 times
57
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
C code
#include <stdio.h>
int main()
{
int i; //for outer loop counter
int j; //for inner loop counter
1. Till the inner loop condition fails the control iterates inside the inner loop, when
inner loop condition fails the control moves to the outer loop
2. When ever the control is moving from outer loop to inner loop the value
2.7.1 FUNCTIONS
2.7.1 Functions
58
Function means, a large program can be divided into a series of individual related
programs called modules. These modules are called functions.
function is set of program to perform some specific and well defined tasks.
a) Reusability: The function writes once and use many times is called Reusability.
b) Modular Program Approach: A large program is divided into smaller sub
programs. so that each sub program performs a specific task. This approach makes
the program development more manageable.
c) Efficiency: means by avoiding redundant instructions the size of program can be
reduced. Which increase efficiency of program.
d) Function sharing: A function can be shared by many programmers.
e) It is very easy to identify the logical errors and correct.
f) It is very easy to read and understand.
2.7.3 The functions can be classified into two categories. Or types of functions
Advantages :
1 : The programmer’s job is made easier because the functions are already available.
2 : The library functions can be used whenever required.
Disadvantages : The standared library functions are limited, programmes can not
completely on these library functions. The programmer has to write his own programs.
2 : User Defined Functions : These functions which are written by the programmer to
do some specific tasks are called User Defined Functions.
2 : Function Call : The function can be called by simply using the function name.
Syntax : function-name();
function-name(parameters);
return value = function-name(parameters);
3 : Function Definition : The program module that is written to achieve a specific task is
called function definition.
#include<stdio.h> {
void add(); //function int a,b,c;
declaration/prototype printf(“Enter the values of a and b”);
void main() scanf(“%d%d”,&a,&b);
{ c=a+b;
add(); //Function call printf(“the sum is %d”,c);
} }
void add() // function definition
61
Output : 5
5
Enter the values of a and b the sum is 10
Ex : main()
{
fun1( a , b ); //Calling function / main fun
}
fun1( x, y ) //called function / user def fun
{
..... .
}
Where
a, b are the Actual Parameters
62
1 : Local Variable : The local variables are defined within the body of the function or
block. These variables can access by that function only, other functions can not access
these ariables.
Ex : fun1(int a,int b)
{
int c,d; // Here c and d are the Local variable
63
}
2 : Global Variable : Global variables are defined outside the main() function and
multiple functions can use these variables.
Return Statement : The return statement may or may not send back any values to the
calling function(main program).
Syntax : return; // does not return any value
or
return(exp); // the specified exp value to calling function.
A function can contain more than one return statements, when the return value can return
values based on certain condition.
If a function can return some values other than int type, then we must specify the
data type to be return.
1) In this category, there is no data transfer between the calling function and called
function.
2) But there is flow of control from calling function to the called function.
3) When no parameters are there , the function cannot receive any value from the calling
function.
64
4) When the function does not return a value, the calling function cannot receive any
value from the called function.
1) In this category, there is no data transfer between the calling function and called
function.
2) But there is data transfer from called function to the calling function.
3) When no parameters are there , the function cannot receive any values from the
calling function.
4) When the function returns a value, the calling function receives one value from the
called function.
} 5
5
Output : sum= 10
enter the values of a and b
1) In this category, there is data transfer from the calling function to the called function
using parameters.
2) But there is no data transfer from called function to the calling function.
3) When parameters are there , the function can receive any values from the calling
function.
4) When the function does not return a value, the calling function cannot receive any
value from the called function.
Ex : #include<stdio.h> }
#include<conio.h>
void sum(int a,int b); void sum(int a,int b)
void main()
{ {
int m,n; int c;
clrscr(); c=a+b;
printf("Enter m and n printf("sum=%d",c);
values:"); }
scanf("%d Output :
%d",&m,&n); Enter the values of a and b
sum(m,n); 5
getch(); 5
sum= 10
1) In this category, there is data transfer from the calling function to the called function
using parameters.
2) But there is no data transfer from called function to the calling function.
66
3) When parameters are there, the function can receive any values from the calling
function.
4) When the function returns a value, the calling function receives a value from the
called function.
Ex : getch();
#include<stdio.h> }
#include<conio.h> int sum(int a,int b)
int sum(int a,int b); {
void main() int c;
{ c=a+b;
int m,n,c; return c;
clrscr(); }
printf("Enter m and n
values"); Output :
scanf("%d%d",&m,&n);
c=sum(m,n); Enter the values of a and b
5
printf("sum=%d",c); 5
sum= 10
2.8 Recursion
A function that calls itself is known as a recursive function. And, this technique is known
as recursion.
void main()
{
recursion();
}
void recursion()
67
{
recursion(); /* function calls itself */
}
The C programming language supports recursion, i.e., a function to call itself. But while
using recursion, programmers need to be careful to define an exit condition from the
function, otherwise it will go into an infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as
calculating the factorial of a number
#include<stdio.h>
int factorial(int); getch();
int main() }
{ int factorial(n)
int factorial(int n); {
int fact; int fact;
clrscr(); if(n==1)
printf(“enter the number”); return 1;
scanf(“%d”,&n); else
fact=factoria(n); fact=n*factorial(n-1);
printf("factorial of a given number is return fact;
%d",fact); }
O/P: Enter the number 5 : factorial of a given number is 120
Whenever we are using recursive functions in our programming there are some
limitations
1) The recursive functions may involve extensive overhead because they use function
calls repeatedly.
2) Whenever we make a call we need to use some separate memory allocations
3) If the program has a large number of recursive calls then we need to run the
program may be out of memory.
1. It requires extra storage space. The recursive calls and automatic variables are
stored on the stack. For every recursive calls separate memory is allocated to
automatic variables with the same name.
2. Too many recursive functions there may be confusion in the code.
3. The recursion function is not efficient in execution speed and time.
4. Recursive solution is always logical and it is very difficult to trace. (Debug and
understand). Recursion takes a lot of stack space.
2.9 ARRAYS
Definition:
C supports a derived data type known as array that can be used to handle large
amounts of data (multiple values) at a time.
An array is a collection of elements of the same data type, which share a common
name.
Array elements are always stored in contiguous memory locations.
Each element in the group is referred by its position called index.
The first element in the array is numbered 0, so the last element is one less than the
size of the array.
Before using an array its type and dimension must be declared, so that the compiler
will know what kind of an array and how large an array.
A list of items can be given one variable name using only one subscript and such a
variable is called one-dimensional array or single-dimensional variable.
datatype array-name[size];
The data-type specifies the type of elements such as int, float or char. And the size
indicates the maximum number of elements that can be stored in that array.
Eg:
int a[5] ; here a is an array containing 5 integer elements.
float height[10]; here height is array containing 10 real elements.
70
Note: C language character strings are as simple as array of characters. And every string
should be terminated by null character (‘\0’).
After an array is declared its elements must be initialized. Otherwise they will
contain garbage values. An array can be initialized at either of the following stages.
At compile time
At run time
We can initialize the elements of arrays in the same way as the ordinary variables
when they are declared. The values in the list must and should be separated by comma.
Eg:
C allows us to define the data in the form of table of items by using two-
dimensional arrays.
Eg: int a [ 3] [ 4 ] ; Here a is two dimensional array with row size 3 and column
size 4., and the total elements we can store in this array a is 12 (i.e. 3 * 4 ).
Each dimension of the array is indexed from zero to its maximum size minus one;
the first index selects the row and the second index selects the column with in that row.
Two dimensional arrays are stored in memory as follows:
71
Eg:
#include<stdio.h>
void main()
{
int arr[4];
int i, j;
printf("Enter array element");
for(i = 0; i < 4; i++)
{
scanf("%d", &arr[i]); //Run time array initialization
}
for(j = 0; j < 4; j++)
72
{
printf("%d\n", arr[j]);
}
}
#include<stdio.h>
Void main ()
{
int arr[3][4];
int i, j, k;
printf("Enter array element");
for(i = 0; i < 3;i++)
{
for(j = 0; j < 4; j++)
{
scanf("%d", &arr[i][j]);
}
}
for(i = 0; i < 3; i++)
{
for(j = 0; j < 4; j++)
{
printf("%d", arr[i][j]);
}
}
}
#include<stdio.h>
void main()
{
int i;
int arr[3] = {2, 3, 4}; // Compile time array initialization
printf("%d %d %d \t",arr[0],arr[1],arr[2]);
}
O/P: 2 3 4
#include<stdio.h>
void main()
{
int i;
int arr[3] ;
printf(“Enter array elements “); // //Run time array initialization
scanf("%d %d %d \t",&arr[0],&arr[1],&arr[2]);
printf("%d %d %d \t",arr[0],arr[1],arr[2]);
}
O/P : Enter array elements 1 2 3
the elements are : 1 2 3
O/P: 2 3 4
3.1 STRINGS: or Character Arrays
A string is an array of characters. (Or) A string is a one-dimensional array of characters
terminated by a null character (‘\0’).
Each character of the string occupies one-byte of memory. The characters of the string
are stored in contiguous memory locations.
The input function scanf ( ) can be used with %s format specification to read a
string.
Eg: char name[30];
scanf(“%s”, name);
The scanf() function to read single word.
So multi word strings can’t read by using scanf() function.
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
75
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
Operators can’t work with strings directly. So to manipulate strings we have a large
number of string handling functions in C standard library and the responsible header file
is “string.h”. Some of those functions are:
strcpy ( ), strcmp ( ), strcat ( ), strlen ( ), strrev ( ) etc.
strcpy( ):- It is to copy one string into another, and it returns the resultant string.
Syntax: strcpy ( string1, string2);
String2 is copied into string1.
76
strcmp( ):- It is to compare two strings to check their equality. If they are equal it
returns zero, otherwise it returns the numeric difference between the first non matching
characters in the strings. (i.e. +ve if first one is greater, -ve if first one is lesser).
Syntax: strcmp (string1, string2);
Eg: char city1[10] = “HYDERABAD”;
char city2[12] = “BANGLORE”;
strcmp (city1, city2);
Here city1 and city2 are compared, and returns the numeric difference between ASCII
value of ‘H’ and ASCII value of ‘B’ as they are not equal.
Strcmp(“RAM”,ROM”); It returns some –ve value.
Strcmp(“RAM”,RAM”): It returns 0 as they are equal.
strcat ( ):- This function is used to join two strings together, and it returns the resultant
string.
Syntax: strcat ( string1, string2);
String1 is appended with string2 by removing the null character of string1 and string2
remains unchanged. The resultant string is stored in string1.
Eg: char city1[10] = “HELLO”;
char city2[12] = “WORLD”;
strcat (city1, city2);
Here city2 is appended to city1. So city1= “HELLOWORLD” and city2=”WORLD”.
strlen( ):- It is to find out the length of the given string and it returns an integer value,
that is the number of characters in the given string. It takes only one parameter
Syntax: strlen ( string1);
It gives the length of string1.
Eg: char city[10] = “HYDERABAD”;
strlen (city); it gives the value 9.
77
strrev ( ):- This function is to find out the reverse of a given string.
Syntax: strrev (string);
Eg: char city[10] = “HYDERABAD”;
strrev (city); it give the string “DABAREDYH”
void main()
{
char name[15],*ch; Output:
printf(“enter your name: ”);
gets(name); enter your name: dennis
ch=name; dennis
printf("%s",*ch);
}
3.4 Arrays of strings:
Consider, for example, the need to store the days of the week in their textual format. We
could create a two-dimensional array of seven days by ten characters, but this wastes
space.
Program on array of strings
#include<stdio.h> int i;
#include<conio.h> char color[4]
#include<string.h> [10]={"Red","Green","Blue","yellow"};
void main() clrscr();
{ printf("the entered array is : \n");
for(i=0;i<4;i++)
79
{ O/P:
printf("%s\n ",color+i); Red
} Green
getch(); Blue
} yellow
The various input and output functions that are associated with can be classified as
I / O Functions
1 : getchar() function : A single character can be given to the computer using ‘C’ input
library function getchar().
Syntax : char variable=getchar();
Example program
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char x;
80
clrscr();
x=getchar();
printf("th given character is%c",x);
getch();
}
The getchar() function is written in standared I/O library. It reads a single character
from a standared input device. This function do not require any arguments, through a pair
of parantheses, must follow the statements getchar().
2 : putchar() function :The putchar() function is used to display one character at a time
on the standared output device. This function does the reverse operation of the single
character input function.
Syntax : putchar(character varaiable);
Example program
#include<stdio.h>
void main()
{
int c;
printf("enter a character");
c=getchar();
putchar(c);
getch();
}
3 : gets() : The gets() function is used to read the string (String is a group of characters)
from the standard input device (keyboard).
Syntax : gets(char type of array variable);
4 : puts() :The puts() function is used to display the string to the standared output device
(Monitor).
Syntax : puts(char type of array variable);
Example program on gets and puts
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char x[20];
clrscr();
printf("enter string\n");
81
gets(x);
puts("the string stored in x is:");
puts(x);
getch();
}
getch() function :The getch function reads a single character directly from the keyboard,
without echoing to the screen. Example program
void main()
{
char ch;
ch = getch();
printf("Input Char Is :%c",ch);
}
Syntax : int getch();
getche() function :The getche() function reads a single character from the keyboard and
echoes it to the current text window.
Syntax : int getche();
Example program
void main()
{
char ch;
ch = getche();
printf("Input Char Is :%c",ch);
}
getc() function : This function is used to accept a single character from the standared
input to a character variable.
Syntax : character variable=getc();
putc() function :This function is used to display a single character in a character variable
to standared output device.
Syntax : putc(character variable);
Ex:
#include <stdio.h>
int main()
{
char ch;
FILE *fp;
82
#include<stdio.h>
#include<conio.h>
void main()
{
char a[22],b[22];
clrscr();
printf("Enter string\n");
gets(a);
strcpy(b,a);
strrev(b);
if(strcmp(a,b)==0)
printf("string is palindrome");
else
printf("string is not a palindrome");
getch();
}
O/P:
Enter string : amma
string is palindrome
Header file <ctype.h> includes numerous standard library functions to handle characters
(especially test characters).
You will find various library functions defined under <ctype.h> for character handling
All C inbuilt functions which are declared in ctype.h header file are given below.
Function Description
3.7 Math.h
The standard math library, math.h, contains a large number of mathematical tools. This
includes trigonometry (sine, cosine, tangent, etc.), exponential functions, logarithmic
functions, absolute values, square roots, etc. We've included a table for reference, but let's
look at a few commonly used functions.
Function Description
setdate() This function used to modify the system date
getdate() This function is used to get the CPU time
clock() This function is used to get current system time
This function is used to get current system time as
time()
structure
This function is used to get the difference between two
difftime()
given times
strftime() This function is used to modify the actual time format
mktime() This function interprets tm structure as calendar time
This function shares the tm structure that contains date
localtime()
and time informations
This function shares the tm structure that contains date
gmtime()
and time informations
This function is used to return string that contains date
ctime()
and time informations
Tm structure contents are interpreted by this function
asctime()
as calendar time. This time is converted into string.
POINTERS:
85
3.9.1: INTRODUCTION
A pointer is a derived data type in C
Pointer is a variable which contains memory addresses as its value.
Pointer which can hold the address of primitive data type like char, int, float,
double or user defined data type like function, pointer etc. or derived data type like
array, structure, union, enum.
Pointer stores a reference to another value.
Pointers are frequently used in C language, as they offer a number of advantages to
the programmers.
They are:
3.9.2.Uses of pointers :
a. Pointers reduce the length and complexity of programs.
b. They increase the execution speed and thus reduce the program execution time.
Dynamic memory allocation
In c language, we can dynamically allocate memory using malloc() and calloc() functions
where the pointer is used.
Arrays, Functions, and Structures
Pointers in c language are widely used in arrays, functions, and structures. It reduces the
code and improves the performance.
Pointers provide direct access to memory
They save memory space. Instead of referring values we can refer to the addresses at
which they are stored.
Handling array values is easy using pointer.
We must ensure that the pointer variable always pointing to the corresponding type
of data.
Eg: float a; int x, *p;
p = &a this is not allowed as p is integer pointer and a is float variable.
We could also define a pointer variable with an initial value of NULL or zero.
int *p = NULL; int *p = 0;
o/p:
Sample Code
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[5]={5,3,6,2,7};
int l,*p,*q;
clrscr();
p=&arr[0]; q=&arr[3];
printf("adress of p is : %u\n",p);
p=p+2;
88
O/P :
A pointer to a pointer is a pointer to store the address of another pointer. Such pointer is
known as a double pointer (pointer to pointer).
The first pointer is used to store the address of a variable whereas the second pointer is
used to store the address of the first pointer.
Let's understand it by the diagram given below.
#include<stdio.h>
#include<conio.h>
void main()
{
int x=10, *p,**q;
clrscr();
p=&x;
q=&p;
printf("x values is %d \n",x);
printf("address of x is %u\n",&x);
printf("values of p is %u\n",p);
printf("address of p %u \n",&p);
printf("value at pointer p is %d",*p);
printf("value of q % u \n",q);
printf("the address of q is %u \n",&q);
printf("the value of x by using pointer to pointer %d",**q);
getch();
}
O/P
90
1. Call by Reference
2. Call by Value
Call by Value
1. While Passing Parameters using call by value , xerox copy of original parameter
is created and passed to the called function.
2. Any update made inside method will not affect the original value of variable in
calling function.
3. In the above example num1 and num2 are the original values and xerox copy of
these values is passed to the function and these values are copied into
number1,number2 variable of sum function respectively.
4. As their scope is limited to only function so they cannot alter the values inside
main function.
Example program :
91
#include<stdio.h>
#include<conio.h>
void swap(int ,int );
void main()
{
int i,j; clrscr();
i=10;j=20;
swap(i,j);
printf("After swapping in main function:%d %d\n",i,j);
getch();
}
void swap(int a,int b)
{
int temp;
temp=a;
a=b;
b=temp;
printf("values after swapping in user function : %d %d\n",a,b);
}
O/P:
After swapping in main function : 10 20
Values after swapping in user function: 20 10
Call by Address / call by reference
1. While passing parameter using call by address scheme , we are passing the actual
address of the variable to the called function.
2. Any updates made inside the called function will modify the original copy since
we are directly modifying the content of the exact memory location.
Example program:
#include<stdio.h>
#include<conio.h>
void swap(int* ,int* );
void main()
{
int i,j; clrscr();
i=10;j=20;
swap(&i,&j);
printf("After swapping in main function:%d %d\n",i,j);
getch();
92
}
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
printf("values after swapping in user function : %d %d\n",*a,*b);
}
Output :
After swapping in main function : 20 10
values after swapping in user function :20 10
Example program :
#include<stdio.h>
void main()
{
int a=20;
float b=20.5;
char c='c';
void *p;
clrscr();
p=&a;
printf("value of int is : %d\n",*((int*)p));
p=&b;
printf("value of float is :%f\n",*((float*)p));
p=&c;
printf("value of char is :%c",*((char*)p));
93
getch();
}
Output :
value of int is : 20
value of float is :20.500000
value of char is : c
In C, the exact size of array is unknown until compile time, i.e., the time when a compiler
compiles your code into a computer understandable language. So, sometimes the size of
the array can be insufficient or more than required.
Dynamic memory allocation allows your program to obtain more memory space while
running, or to release it if it's not required.
In simple terms, Dynamic memory allocation allows you to manually handle memory
space for your program.
Although, C language inherently does not have any technique to allocate memory
dynamically, there are 4 library functions under "stdlib.h" for dynamic memory
allocation.
1. malloc()
2. calloc()
3. realloc()
4. free()
1)Malloc :
malloc(); function is used for allocating block of memory at runtime. This function
reserves a block of memory of given size and returns a pointer of type void. This means
that we can assign it to any type of pointer using typecasting. If it fails to locate enough
space it returns a NULL pointer. The name malloc stands for "memory allocation".
94
#include <stdio.h>
#include<conio.h>
#include <stdlib.h>
void main()
{
int num, i, *ptr, sum = 0;
clrscr();
printf("Enter number of elements: ");
scanf("%d", &num);
O/P :
Enter number of elements:
5
Enter elements of array:
1 2 3 4 5
95
Sum : 15
2)Calloc :
calloc() is another memory allocation function that is used for allocating memory at
runtime. calloc function is normally used for allocating memory to derived data types
such as arrays and structures. If it fails to locate enough space it returns a NULL pointer.
O/P :
Enter number of elements:
5
Enter elements of array:
1 2 3 4 5
Sum : 15
3)realloc
By using realloc we can increase or decrease the size of an allocated memory block by
calling the function realloc.
The function realloc() reallocates a memory block with a specific new size. If you call
realloc() the size of the memory block pointed to by the pointer is changed to the given
size in bytes. This way you are able to expand and reduce the amount of memory you
want to use
O/P :
4) Free(): free () function frees the allocated memory by malloc (), calloc (), realloc ()
functions and returns the memory to the system.
type cast must be done since this function Same as malloc () function int
returns void pointer int *ptr;ptr = *ptr;ptr = (int*)calloc( 20, 20 *
(int*)malloc(sizeof(int)*20 ); sizeof(int) );
User Defined data Types : Sometimes, the basic set of data types defined in the C
language such as int, float etc. may be insufficient for your application. In circumstances
such as these, you can create your own data types which are based on the standard ones.
1 : Enumerated.
2 : Structure.
3 : Union.
4. typedef
struct <identity>
{
type1 member1;
type2 member2;
: :
: :
typeN memberN;
};
Where,
1 : struct : struct is the keyword which tells the compiler that a structure is being defined.
2 : identity : is the name of the structure.
3 : member1,member2, ….. , memberN are called members of the structure. They are
also called fields of the structure.
4 : The members are declared within curly braces. The members can be any of the data
types such as int, char, flat, etc.
5 : There should be semicolon at the end of closing brace.
Ex : struct student
{
char name[10];
int roll_number;
float average_marks;
};
99
The structure definition does not reserve any space in memory for the
members. So, it is called a structure template and memory will not be allocated for the
template.
Once the structure definition is associated with variables such as, the compiler
allocates memory for the structure variables. The number of bytes allocated for the
variable emp1 is
- 10 bytes are allocated for the field name
- 2 bytes for the field roll_number.
- 4 bytes for the field average_marks.
So, totally 16 bytes are reserved for the variable ece1 and another 16 bytes are reserved
for the variable ece2.
100
Examples
1 : Initilization during structure declartion.
struct student
{
char name[10];
int roll_number;
float average_marks;
};
};
struct student ece1={“abc”, 1000, 75};
struct student ece2={“abc”, 1000, 75};
4.1.4 Accessing Structures : After declaring the structure type, variables and members,
the members of the structure can be accessed by using the structure variable along with
dot(.) operator.
To access any member of a structure, we use the member access operator (.).Use this
Operator in between “Structure name” & “member name”
Syntax : variable.member;
101
Ex : struct student
{
char name[10];
int roll_number;
float average_marks;
};
struct student ece1;
For accessing the structure members from the
Write a program to print the student number, name and marks through accessing
structure elements.
#include<stdio.h>
#include<conio.h> scanf("%d",&s.marks);
struct std printf("Rollno Name Marks \n");
{ printf("%d %s
int no; %d”,s.no,s.name,s.marks);
char name[10]; getch();
int marks;
}; }
struct std s;
void main()
{
float total,avg;
printf("Enter student details:\n");
5 dennis 85
Rollno Name Marks
struct struct-name
{
datatype var1;
datatype var2;
----------
----------
datatype varN;
};
struct struct-name var [ size ];
The following example shows a structure called student that takes the roll number and
name of a student as an input, then stores each record in an array st, which stores three
elements. Each element will hold a mixed record.
#include<stdio.h> {
struct student printf("\nEnter Rollno:");
{ scanf("%d",&st[i].rollno);
int rollno; printf("\nEnter Name:");
char name[10]; scanf("%s",&st[i].name);
}; }
void main() printf("\nStudent Information List:");
{ for(i=0;i<3;i++)
int i; {
struct student st[3];
printf("Enter Records of 3 students");
for(i=0;i<3;i++)
103
4.3 Typedef
Declaration : The typedef is a keyword that allows the programmer to create a new data
type name for an existing data type. So, the purpose of typedef is to redefine the name of
an existing variable type.
Where
1) typedef : is a keyword.
2) data type : any Existing Data Type.
3) New Names for the existing Data Type.
Advantages of typedef :
An enum is defined in the same way as structure with the keyword struct replaced by the
keyword enum and the elements separated by 'comma' as follows.
syntax/declaration of enum
enum enum_name
{
element1,
element2,
element3,
element4,
};
#include <stdio.h>
enum week {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
int main()
{
enum week today;
today = Wednesday;
printf("Day is %d",today);
}
Output Day is 4
The default value of 'sun' will be 0, 'mon' will be 1, 'tue' will be 2 and so on. for example,
if we define the value of tue as 5. So the values of 'wed', 'thurs', 'fri' and 'sat' will become
105
6, 7, 8 and 9 respectively. There will be no effect on the values of sun and mon which
will remain 0 and 1 respectively. Thus the value of thurs i.e. 7 will get printed.
4.5 Union:
Union is a derived type and it is declared like structure. The difference between union
and structure is in terms of storage. In structure each member has its own storage
location, whereas all the members of union use the same location, although a union may
contain many members of different types. When we use union the compiler allocates a
piece of storage that is larger enough to hold. Like structures, union is also declared by
using the keyword union.
Ex : union student
{
int sno,smarks;
char sname[10];
};
Example :
Union un
{
Short a;
Short b;
};
Union un val;
Void main()
{ clrscr();
Val.a=10;
Printf(“value is %d \n”,val.b);
Val.b=20;
Printf(“value is %d”,val.a);
Getch();
}
O/P:
Value is 10
Value is 20
Structure Union
1 : The keword struct is used to define 1 : The keyword union is used to
a structure.y define a union.
2 : When a variable is associated with 2 : When a variable is associated with a
a structure, the compiler allocates the union, the compiler allocates the
memory for each member. The size of memory by considering the size of the
structure is greater than or equal to the largest member. So size of union is
sum of sizes of its members. The equal to the size of largest number.
smaller members may end with unused
slack bytes.
3 : Each member within a structure is 3 : Memory allocated is shared by
assigned unique storage area. individual members of union.
4 : The address of each member will be 4 : The address is same for all the
in asecending order. This indicates that members of a union. This indicates that
107
memory for each member will start at every member begins at offset values.
different offset values.
6 : Individual members can be 6 : Only one member can be accessed
accessed at a time. at a time.
7 : Several members of a structure can 7 : Only the first member of a union
be initialized at once. can be initialized.
4.7 Command Line Argument
Command line argument is a parameter supplied to the program when it is invoked.
Command line argument is an important concept in C programming. It is mostly used
when you need to control your program from outside. command line arguments are
passed to main() method.
Syntax :
int main( int argc, char *argv[])
argc – Number of arguments in the command line including program name
argv[] – This is carrying all the arguments
argc (ARGument Count) is int and stores number of command-line arguments passed
by the user including the name of the program. So if we pass a value to a program, value
of argc would be 2 (one for argument and one for program name)
The value of argc should be non negative.
FILE MANAGEMENT IN C
4.8 FILES:
Data is stored onto the disk and can be retrieve whenever require.
1. TEXT FILES
Text files are the normal .txt files. You can easily create text files using any simple
text editors such as Notepad.
When you open those files, you'll see all the contents within the file as plain text.
You can easily edit or delete the contents.
Text File is Also Called as “Flat File“.
Text File Format is Basic File Format in C Programming.
Text File is simple Sequence of ASCII Characters.
Text File have .txt Extension.
Files with the .txt extension can easily be read or opened by any program that reads
text and, for that reason, are considered universal (or platform independent).
Text Format Contain Mostly English Characters
2. BINARY FILES
Binary files are mostly the .bin files in your computer.
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
Binary Files Contain Information Coded Mostly in Binary Format.
Binary Files are difficult to read for human.
Binary Files can be processed by certain applications or processors.
Humans can read binary files only after processing.
All Executable Files are Binary Files.
Some Examples of the Binary files :
Executable Files
Database files
109
When working with files, you need to declare a pointer of type file. This declaration is
needed for communication between the file and the program.
File can be opened in basic 3 modes : Reading Mode, Writing Mode, Appending Mode
File modes
mode description
r opens a text file in reading mode
w opens or create a text file in writing mode.
a opens a text file in append mode
r+ opens a text file in both reading and writing mode
w+ opens a text file in both reading and writing mode
a+ opens a text file in both reading and writing mode
rb opens a binary file in reading mode
wb opens or create a binary file in writing mode
ab opens a binary file in append mode
rb+ opens a binary file in both reading and writing mode
wb+ opens a binary file in both reading and writing mode
ab+ opens a binary file in both reading and writing mode
4.8.5 Closing a File
The file (both text and binary) should be closed after reading/writing.
a) Formatted functions:-
The file input function fscanf( ) and the file output function fprintf( ) are called formatted
file I/O functions.
Syntaxes:
fprintf (fp, "control string", list_of_var);
b)Unformatted functions:-
The input functions like getc( ), getw( ), and fread( ) are called unformatted file input
functions and putc( ), putw( ), and fwrite( ) functions are unformatted file output
functions. Each and every function is having its own syntax and meaning.
Fopen function:
The general format for declaring and opening la file is
112
FILE *fp;
Fp = fopen ( “file name”, “mode” );
Where the variable fp has a pointer to the data type File opens the File name a
and pointer assigns an identifier to the File type pointer fp. This pointer which contains
all the information about the File subsequently used as a communication link between the
system used as a communication between the system and the program.
Both ‘file name’ and ‘mode’ are specified as string they should be enclosed in ‘’ ‘’.
Where fp1,fp2 are pointer the ‘fp1’ is opens the File named as data for reading
mode only then fp2 opens the file named as ‘result for writing made only
Putw(num,fp);
Where ‘fp’ is a file pointer associated with a file that has been opened for writing.
The control string contains output specifications for the items in the list. The list may be
including variable constants and strings.
Ex : fprintf (fp1, "%s %d %f”, name age,7.5);
The fscanf function : The fscanf function is used to read data items to the file whose
pointer is opened in the reading mode. fscanf function performs I/O operations on files.
The general form of fscanf is
This statement reading of the items in the list from the file specified by fp. The
control string contains input specifications for the items in the list.
Where ‘n’ gives the relative offset (in bytes) of the current position. This means
that ‘n’ bytes have already read.
114
The Rewind function :
It takes a file pointer and resets the position to the start of the (in bytes). The statement is
Rewind (fp);
N = ftell(fp);
It will assign ‘o’ to n’ because the file position has been set to the start of the file
by rewinded. i.e.., The first byte in the file is numbered as ‘o’ second as ‘1’ and a so on.
Fseek function :
It is used to move the file position to a desired location within the file It takes the
following form
Here ‘file pointer’ is a pointer to the file, ‘offset’ is a number or variable of type
‘long’, and position is an integer variable. The offset specifies the positions (bytes) to be
moved from the location specified by position.
Syntax:
fputc(ch,fp)
Reading File : fgetc() function
The fgetc() function returns a single character from the file. It gets a character from the
stream. It returns EOF at the end of file.
Syntax:
fgetc(fp)
printf("\nEnter percentage of
student : ");
#include<stdio.h>
struct stud
{ scanf("%f",&s.per);
int rno; fprintf(fp,"%d\n%s\n%s\n
float per; %f",s.rno,s.name,s.add,s.per);
char name[20],add[20]; printf("\nRecord stored in file...");
}s; fclose(fp);
void main() }
{
FILE *fp;
fp=fopen("student.txt","w");
ftell( ),
and rewind( ).
ftell( ) function:- If we wish to know where the file pointer is positioned right now, we
can use the function ftell. ftell takes a file pointer as an argument, and it returns the
position as long int which is an offset from the beginning of the file. It takes the
following form:
syntax: n = ftell(fp);
Note : for binary file programs save file as .bin and change mode to rb/wb/ab