Beruflich Dokumente
Kultur Dokumente
C-language
Computer:
Computer is an electronic machine which accepts raw data as the input,
process the data and gives information as the output.
Language:
It is the media of communication between any two or more. It may
be oral or signs.
What is meant by computer language?
It is nothing but communicating with the system by the user or
programmer to perform his task or fulfill his job.
Computers basics:
There is only 3 basic concepts about computer, that is noting
input -> process->output.
Input:
The inputs are given to the system by using input devices such as
keyboard, mouse.
Output:
The output is viewed on the output devices such as VDU (video
display unit) or printer.
Process:
Page 2 of 86
This task is performed by the CPU(Central Process Unit).
It is divided into 3 parts.
1. A.L.U ARTHMETIC AND LOGICAL UNIT
2. C.U- CONTROL UNIT
3. M.U- MEMORY UNIT
ALU performs the actual number crunching and logical operations.
CU controls the total process how to input and how to store and
how to operate.
MU is used to store the data.
Parts of Computers:
Mainly 2 parts are exit in computers one is HARDWARE(H/W) and
SOFTWARE(S/W).
What
o
What
o
Hardware:
Operating system:
Page 3 of 86
It is an interface between user and computer in other words Operating
system is a complex set of programs which manages the resources of a
computer resources include input, output, processor etc
Language:
A programming language consists a set of executable instructions.
Package:
It is designed by any other language with limited resources
Software :
Software is said to be collection of programs. This can be categorized as 2
parts.
1. System S/W
2. Application S/w
System S/W:
o Those S/w are used as the interface between system and user are
called as System S/W.
Eg: Operating systems, Drivers, Utilities .
Application S/w
o Those S/w are used for the special purpose of the user.
Eg: Packages(like accounting packages and ms-office).
Languages:
But to implement or develop the S/Ws is done by the programming
languages.
Syntax: The structure of the program code.
Eg: Add(10,20) or 10+20; it is different for every languages.
Semantic: the actual meaning of the syntax.
Eg: Add(10,20) add 10 and 20 integers.
Programming Languages are of 3 types. They are
Machine Language
Middle level language or Assembly Language
High level Languages
Machine Languages are completely based on the binary Language(mean 0s
and 1s). this language is easily understood by computers but very hard for
developer. Error checking is very tough job.
Page 4 of 86
Middle languages are use some small keywords, those reduce the
programmers code to develop. These are little bit easy for developers and
also systems but not completely.
High level languages are completely in natural English words. So very easy
for the developer but very hard to the system.
Language translators:
High and middle languages are to be translated to machine language code
by Language translators,
Because system only understood machine languages only.
There are 3 types of translators are present.
Assembler: This translator translates assembly level code to machine level
code.
Compiler: Compiler translates entire high level program code to machine level
code at a time.
Interpreter : interpreter translates high level program code to machine level
code line by line.
Note:
If compiler is used, first complier checks for Syntactical errors and
displays the errors. If no errors are occurred then translates the program.
If Interpreter is used, for execution of one statement it checks the next
statement if it is syntactically correct or not.
ASCII character
American Standard code for information and Interchange
There are 256 distinct characters used by the micro computers their
values range from 0 to 255. These can be grouped as under
Character type
No.of character
A to Z
26
a to z
26
digits
0-9
special Symbols
32
control characters
34
graphics characters
128
-------------------
Page 5 of 86
256
Out of the 256 characters, the first 128 are ASCII characters and the next
are called extended ASXII characters. Each ASCII Character as a unique
appearance.
A to Z
65 to 90
a to z
97 to 122
o to 9
48 to 57
Enter
13
Space Bar
32
Tab
Backspace
Debugging:
The process of correcting errors in a program is called as debugging.
Various Steps in Application/Program development:
1. Problem definition
2. Analysis and design
3. Algorithm
4. Flow chart
5. Coding and Implementation
6. Debugging and testing
7. Documentation
Problem Definition:
Problem Definition phase is a clear understanding of exactly what is
needed for creating to a workful solution. We must know exactly what we want to
do before we begin to do it. Define the problem means Understanding the
problem. It involves the 3 specifications regarding a problem solution
o
Input Specifications
Output Specifications
Processing
Page 6 of 86
Before going to make the final solutions for the problem, the problem must
be analyzed outlines solutions prepared for simple problems but in case of
complex problems the main problem is divided into sub problems called
modulus. These sub problems can be handled can be solve independently when
the task is too large, it always better to analysis. The tasks such that it can be
divided into no.of module and solutions for each moduleue.
Algorithm:
Once the problem is divided into no.of modulus. The Logic for solving each
module can be developed. The logic is expressed step by step. A step by step
processor to solve the given problems know as ALGORITHM. An algorithm is
defined as a final set of steps which accomplish a particular task. An algorithm
can be described in a natural language such as English.
Flow Chart:
After the completion of algorithm the program flow can be visualized by
drawing the FLOW CHART. A flow chart is nothing but a graphical of symbolic
representation o how instructions will be executed one after the another.
Coding and implementation:
Coding is a process of converting the algorithm solution or flows chart in
to a computer program. In this process each and every step of algorithm will be
converted in to instructions of selected computer programming language. Before
selecting a programming language. Before selected computer programming
language we must follow the 3 following considerations
o
Limitations of computer
Syntax errors
Logical errors
Runtime errors
Page 7 of 86
It is the most important aspect of the programming. it is a continues
process to keep the copy of all the phases invoked in problem definition
,analysis, design ,algorithm, flowchart, coding and implementation, debugging &
testing are the parts of the Documentation. This phase involves to producing a
written document for the users.
Language paradigms:
Programming style
Abstraction Employed
Procedure oriented
algorithms
Object Oriented
Logic Oriented
Rule Oriented
Constraint Oriented
Invariant relationship
Monolithic Programming
Procedure Programming
Structured Programming
Object Oriented Programming
Monolithic Programming :
The programs written in these languages exhibit relatively flat physical
structure. They consists only global data and sequential code.
Page 8 of 86
Only Global Data
1..
2.
Goto 100
.
Goto 55
..
Goto 3
.
Goto 45
..
100
Eg: Assembly Language, BASIC
Procedure Programming:
Programs are organized in the form of subroutines and all data items
are global
Program controls are through jumps and calls to subroutines
Subroutines are abstracted to avoid repetitions
Suitable for medium sized software applications
Difficult to maintain and enhance the program code
Page 9 of 86
Glob
al
Data
Sub
Progr
ams
Structured Programming:
Page 10 of 86
Global
Data
Modul
e1
Modul
e2
Sub
Programs
Modul
e3
Page 11 of 86
Object
A
Object
B
Object
B
Applications
Major languages
Other languages
Business
COBOL
Assembler
Scientific
FORTRAN
ALGOL, BASIC
System
Assembler
JOVIAL,FORTH
AI
LISP
SNOBOL
Business
C, PL/I, 4GLs
Scientific
FORTRAN, C, C++,
Java
BASIC
Today
Page 12 of 86
System
C, C++, Java
LISP, Prolog
Publishing
Process
New paradigms
ML, Smalltalk
Eiffel
History of C- Language:
C is a programming language it is designed by DENNIS RITCHIE in 1972 at AT & T
(American Telephone and Telegraphs) Bell labs ,USA.
C is a most popular general purpose programming language. We can use the c
language designed any type of applications. Mainly we are using the c language to
implement system software those are COMPILERS, TEXT EDITORS, NETWORK DRIVERS,
DATABASES and finally the OPERATING SYSTEMS.
Brief history of c language:
In 1960s COBOL was being used for commercial applications and FORTRAN for
scientific and Engineering applications are this stage people started to develop a
language which is suitable for all possible applications. There fore an International
committee was setup to develop such a language ALGOL60 was released it was not
popular because it seemed too general to reduce the generality a new language called
CPL (Combined Programming Language) was developed at CAMBRIDGE UNIVERSITY. It
has very less features than some other features were
C Language
Page 13 of 86
Features of C language
1. c is a structure programming language with fundamental flow control
construction.
2. C is high portable programming language. And c programs are run on
another with or without any modifications.
3. C is simple and versatile programming language.
4. Programs written in c are efficient and fast.
5. C improves by itself it has several predefined functions.
6. C has a rich set of operators
7. C has only 32 key words
8. C permits all data conversions and mixed more operations.
9. C easily manipulates bits bytes and addresses
10.Dynamic memory allocation is possible with C.
11.Recursive functions called for algorithmic approach is possible with c.
12.Mainly we are using the c to implement system softwares those are
compilers, Text readers, Network drivers, data bases and finally the
operating systems.
13.C compiler combines the capabilities of an assembly level language with
the features of high level language. So it is called as middle level
language.
Impotent points:
1. C was basically designed for the UNIX operating systems 93% of which is
written in c.
2. c is a case sensitive programming language. C statements are entered in
small case letters only
3. Every c statements must be terminated by a ; except preprocessor
statements and functions definition.
4. c is a function oriented programming language. Any c program contains
one or more functions minimum one functions necessary by the name
called main with out main with out main we cant execute c program.
5. A function is represented by a function name with a pair of parenthesis.
C program Execution
Page 14 of 86
Object File(.obj)
C source program
Compiler
(.c file)
Execute File
(.exe)
Linker
C
Library Files
Processor
Start program Execution
O/P
Loading
Primary
Memory
(RAM)
Once the coding is completed, the program is feed into the computer
using a compiler to produce equivalent machine language code. In c program
compilation two parts are there namely Compiler and Linker.
The C compiler receives source program (file) as input and converts into
object file. Then the linker receives this object file and linking with the c libraries
after linking it produces a Executable files. After the creation of executable file
that starts the program execution and loading the information in to the primary
memory through loading process. After loading the information the processor
process the information and gives the output.
Page 15 of 86
Statements
}
[Sub Programming section]
(user defined functions)
Document Section:
This section consists a set of comment lines giving the name of the
program author name and some other details about the program.
The variables that are used in more than one function are called global
variables and these variables are called in the Global Declaration Section.
Every C program must have one main function. This section consists 2
parts namely
1. Local declaration section.
2. Statements.
The local declaration section declares all the variables used in statements.
The Statements part consists A sequence of executable instructions. These two
Page 16 of 86
parts must appear between the opening and closing curly brasses { }. The
program execution begins at opening bras and ends at the closing bras.
Comments:
Un executable lines in a programmer called comments. These lines are
skipped by the compiler.
C- comments:
/*----------------------------------------------------------------- */
(for both multi line and single line comments.)
Note:
If c++ editor use single line comments ( // ).
// ---------------------
#include:
This is a preprocessor file inclusion directive and is used to include header
files. It provides instructions to the compiler to link the functions from the system
library.
Page 17 of 86
C-Tokens
Tokens:
The smallest unit part of a program language, that is not to be divided is
called as Token. Every language has its own tokens.
Alphabets
C-Tokens:
Words
Sentences
Paragraphs
Page 18 of 86
Key Words:
Key word is the predefined word, whose definition is already given to the
compilers.
These keywords reduce the stress on the programmer to generate the code.
Identifier:
Identifier is nothing but naming. i.e. The name given to the memory block
present in memory( generally main). Identification of every thing such as
variables, constants, functions etc are identified by using the identifier only.
Syntax:
Page 19 of 86
Type name;
Ex:
int a;
void add();
Syntax:
Data_type var_name;
Data_type iden-1,iden-2,..iden-n.
Ex:
int a;
char ch;
Page 20 of 86
Constants:Constant in c refer to fixed value that dont change during the execution of
a program . C supports the following constants.
Integer constantans
Real Constants
Character constants
String constants
Constants are those whose value does not varies (not changes) at the time
of program execution. i.e. value in the memory block doesnt changes.
o
o
o
o
Syntax:
const Data_type var_name;
Ex:
const int a;
const char ch;
Note: const is the keyword to create constants in c-languages.
Constants are of 2 types. Namely Numeric constants and Character
constants.
Strings:-
Page 21 of 86
Syntax:
char string_name[ size ];
ex:
char st[25];
Operators:
Arithmetic operators
Logical operators
Relational operators
Bitwise Operators.etc
Special Characters:
All Characters other than Alphabets and digits are treated as special
characters.
Data types:-
Page 22 of 86
four
fundamental
data
types
namely
Integer:
(int)
It is a positive, negative and whole values but not a decimal numbers.
Eg:
-75, 0 , 25 etc
Float:
The numbers which are stored in the form of floating point representation
is called as float data type.
Eg:
10.25, 125.56,0.123,-0.567
Double:
The numbers which are stored in the form of double precision floating
point representation is called as double data type.
Eg:
2367.1234, -12345.687957 etc
Page 23 of 86
These are created from the basic integers, characters and floating data
types. The examples of derived data types are Arrays, Pointers, Structures,
Unions etc.
Typedef(Type definition)
ENUM (Enumerated data type)
A type modifier alters the meaning of the base data type to yield a new
type.
Each of these type modifiers can be applied to the base type int.
The Modifiers signed and unsigned can also be applied to the base type
char.
In addition long can be applied to double.
Data Type
Format Specifier
Accessibility Range
unsigned char
%c
0 to 255
char
%c
-128..0.127
int
%d
-32768 to -32767
unsigned int
%u
0 to 65535
%ld
-214783548 to 214783647
unsigned long
(or) unsigned
long int
%lu
0 to 4294967295
float
%f
double
%lf
1.7*(10**-388) to 1.7*(10**388)
long double
%Lf
10
3.4*(10**-4932) to
1.1*(10**4932
char[] -string
%s
Page 24 of 86
Initialization:
AT the time of declaring a variable we can store some data into that
variable is called as Initialization.
Eg:
int n=100;
float ft=24.67;
char ch=c;
int a=10,b=20;
int x=100,y,z;
Sample C Program
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf(welcome to c programming);
}
Printf():
Page 25 of 86
printf(welcome to c programming);
This printf statements are used to print messages and the value contained
in variable on screen.
Clrscr();
It clears the text mode window.
Declaration:
void clrscr();
Note:
In c language all the declarations will be done before the executable
statement.
Option
Key
Save
F2
Page 26 of 86
Open
F3
Compile
Alt+ F9
Run
Ctrl+ F9
Output
Alt + F5
Close File
Alt + F3
Full Screen
F5
Switch betn 2
windows
F6
Quit
Alt + x
Getch():
It is a function and is used to get a character from keyboard but it does not
echo the screen.
This is used to reduce the key press of Alt + F5 key to see the output.
Declaration of Constants:
\n
New line
\t
Horizontal tab(8
spaces)
\v
Vertical Tab
\b
Back Space
\r
Carriage written
\a
Alert(Beep
Sound)
Page 27 of 86
Constants refers to fixed values that donot change during the execution of
a program.
Const:
It is a key word and is used to define constants
Declaration:
const datatype identifier=value; or
const datatype ide_1=val_1,iden_2=val_2;
eg:
const int n=100;
const int x=10,y=25,z=50;
Symbolic Constants:
#define:
It is a preprocessor statement and is used to define symbolic constants.
Syntax:
# define identifier value
Eg:
#define pi 3.14
#define g 9.8
Eg pro:
#include<stdio.h>
#include<conio.h>
#define pi 3.14
#define g 9.8
Void main()
{
clrscr();
Page 28 of 86
printf(pi = %.2f ,pi);
printf(g = %.1f,g);
getch();
}
Note: &n refers the address of variable n, where the value of n to be stored in
memory.
fflush:
It is a function and it flushes the specified stream
Syntax:
int fflush( stream_name);
eg:
fflush(stdin);
flushall:
it flushes all open streams.
Syntax:
int flushall();
Page 29 of 86
Operators in C
Operator:
It is a symbol and it reforms a particular operation.
Operand:
It is a entity on which an operator acts.
Unary Operator:
It requires only a single operator.
Binary Operator:
It requires 2 operators.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Ternary Operators( Conditional Operator)
7. Bitwise Operators
8. Special Operators
Arithmetic Operators:
These are the basic operators in c language. These operators are used for
Arithmetic Operators.
+ Addition
Calculates sum
Subtraction
Calculates Difference
Multiplication
Division
Calculates Product
Calculates Quotient
Page 30 of 86
% Modulus
Calculates Reminder
C-Operators
Operators are of 8 types. They are as follows.
1)
2)
3)
4)
5)
6)
7)
8)
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
Unary Operators
Ternary Operators
Bitwise Operators
Special Operators
Arithmetic Operators:
These are the operators used to perform the arithmetic
operations. Such that addition, subtraction, Multiplication, division,
and modulus(reminder) operators are called as arithmetic Operators.
Operator
Symbol
meaning
Plus
Addition
Minus
Subtraction
Asterisk
Multiplication
Slash
Division
Percentage
Modulus
Relational Operators:
These are the operators derives the relation between the
operands.
Operator
Meaning
<
Less than
<=
>
Greater than
>=
Page 31 of 86
==
Equal to
!=
Not equal to
Logical Operators:
Logical operators are used to perform nested conditions by
combining the statements or conditions.
&&
||
true
P&&Q
P||Q
Assignment Operators:
Assignment operators are used to assign an expression
result to a variable.
= symbol is used for assignment Operation.
Note:
Must assign a known value to a unknown. Ex: a=10.
In case of assignment operators we use short hand expressions.
a=a+10;
a+=10
a=a-10;
a-=10
a=a*10;
a*=10
a=a/10;
a/=10
a=a%10;
a%=10
Page 32 of 86
Unary Operators:
Unary operators are also called as increment/decrement
operators.
There are 4 unary operators are present.
1)
2)
3)
4)
++var
Var++
--var
var--
post incrimination
pre Incrimination
post decrimentation
pre Decrimentation
Ternary Operators:
Ternary operators are used selection of one expression based on
the condition.
Syntax:
exp1?exp2:exp3;
if exp1 is true then exp2 will be executed else exp3 is true.
Bitwise Operators:
Bitwise operators are used at registry level operations those are
directly connected to the registries.
&
Bitwise AND
Bitwise OR
>>
shift right
<<
shift left
bitwise exclusive OR
ones Compliment.
Special Operators:
There are 2 special operators are used as the characters.
1. Comma Operator
2. sizeof Operator
Page 33 of 86
Comma Operator:
This operator is used to link the related expression together. A
comma linked list of expressions are evaluated left to right and the
value of rightmost expression is the value of the combined
expression.
Ex:
Value=(x=10,y=5,x+y=0)
sizeof Operators:
This is a compile time operator and returns the sizeof bytes
occupied by the operand.
Syntax:
Sizeof(var);
are
1.Conditional control statements
2.Unconditional control statements
3.Loop control statements
(1) Conditional control statements:'C' supports five types of
conditional control
Page 34 of 86
...............................................................
statements.They are
(a) Simple if
(b)if-else
(c)Nested if
(d)else_if
(e)switch
Simple if statement
.....................................................................
It is the decision making statement and is used to control the flow of execution
syntax :
..............
if(expression)
{
statements
}
In the statement first the expression will be evaluated and control transfer to the
next
statement.
Page 35 of 86
Note:
.............
In any control statement the statement block contain only a single statements {}
brases are not
neccessary.
Trassing
----------F7 OR F8
Outside
--------RED COLOR
ctrl+f8
inside
outside
(1)./* wap to find the maxium value of given two numbers using Simple if
statement */
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,max;
clrscr();
printf("Enter any two values:");
Scanf("%d%d",&a,&b);
max=a;
if(max<b)
{
Page 36 of 86
max=b;
}
printf("maxium value =%d",max);
getch();
}
output :
...............................
Enter any two values :10 20
max:20
(2)./* wap to find the maxium value of given three numbers using simple if
statements */
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,max;
clrscr();
printf("enter any three values:");
scanf("%d%d%d",&a,&b,&c);
max=a;
if(max<b)
max=b;
if(max<c)
max=c;
printf("maxium value =%d ",max);
getch();
}
OUTPUT
-----------------
Page 37 of 86
Enter any three values :10,20,30
Max =30.
----------------------------------------------------------------------------------------------------------------#include<stdio.h>
#include<conio.h>
void main()
{
int cd,cm,cy,bd,bm,by,d,m,y;
clrscr();
Printf("Enter current Date (dd-mm-yy):");
scanf("%d%d%d%d",&cd&cm&cy);
printf("Enter Date of birth(dd-mm-yyyy):");
scanf("%d%d%d%d",&bd&bm&by);
d=cd-bd;
m=cm-bm;
y=cy-by;
if(d<0)
{
d=d+30;
m--;
}
if(m<0)
{
m=m+12;
y--;
}
printf("age is %d years %d months and %d days",y,m,d);
getch();
Page 38 of 86
}
IF-ELSE STATEMENT:
--------------------------It is an extension of simple if statement .
syntax:
-------if(expr)
{
statements-1;
}
else
{
statements-2;
}
-----------------------------------------------------------------------------------------------------------------i
if the expression is true then the if block statements are executed and else block
statements are
statement is ignored.
/* wap to find the maxium value of given two numbers using if-else statement*/
#include<stdio.h>
#include<conio.h>
void main
{
Page 39 of 86
int a,b,max;
clrscr():
printf("enter any two values:");
scanf("%d%d",&a&b);
if(a>b)
max=a;
else
max=b;
printf("maximum value =%d",max");
getch();
}
----------------------------------------------------------------------------------------------------------------Unconditional Control statements
Break:
It is a unconditional control statement and used to terminate a switch
statement or loop statement .
Syntax:
Break;
Continue:
It is a unconditional control statement, it passes the control.
Syntax:
Continue;
Causes control to pass to the end of the inter most enclosing while, do or
for statement at which point the loop continuation is reevaluated.
Goto statement:
It is an unconditional control statement which is used to alter the
execution of program sequence by transfer of control to the same other part of
the program.
Syntax:
Goto label;
Page 40 of 86
Where label is valid c identifier used to the label of the destination such
that the control could transferred to label.
Syntax:
Label:
Gotoxy:
It is a function, it moves the courser to the specified location in the current
text window.
Syntax:
Void gotoxy(int x,int y);
x- columns -> 80
y rows -> 25.
Note:
If the coordinates are invlid then gotoxy is ignored.
Page 41 of 86
Statements;
}
In this statements the first the text condition will be evaluated. It is true
then the statement block will be executed. After the execution of statement
block the text condition. If it is true then the statement block will be executed
once again. This then process of repeated execution continues until the text
condition finally becomes false.
Do while Loop
It is an alternative form of the while loop. The only difference between
while and do_while is the minimum no.of execution of while is zero, but the
minimum no.of exectuin of do_while is one.
Syntax:
Do
{
}while(test condition);
In do while loop first the statement block will be executed and then test
condition will be evaluated if it is true then the statement block will be executed
once again. This process of repeated execution continuous until the test
condition becomes false.
For Loop
It is the most commonly used loop statement in c language. It si
consisting of 3 expressions
Syntax:
For(exp1;exp2;exp3)
{
Statements;
}
The first expression used to initialize the index. The second expression
used to check whether the loop is continuation or not and.
The third expression is used to change the index for the next iteration.
Page 42 of 86
Nested Loops:
Using a loop statement with in another loop is called as nested loop.
Text modes:Constant
value
TextMode
Lastmode
-1
BW40
C40
color
BW80
C80
color
80 cols
MONO
Monochrome
43 lines
C4350
64
Eg:
#include<stdio.h>
#include<conio.h>
Void main()
{
Clrscr();
Textmode(1);
40 cols
40 cols
40 cols
80 cols
50 lines
Page 43 of 86
Gotoxy(18,12);
Printf(WELCOME):
Getch();
}
_setcursortype:
It selects cursor appearance
Syntax:
Void _setcursortye(int cur_T);
_NOCURSOR (Turns off the cursor)
_SOLIDCURSOR
Eg:
#include<stdio.h>
#include<conio.h>
Void main()
{
Clrscr();
Textmode(1);
_setcursortype(_NOCURSOR);
Textcolor(RED+BLINK);
Textbackground(WHITE);
Gotoxy(18,22);
Cprintf(welcome);
Getch();
}
Text color:
Page 44 of 86
It selects a new character color in textmode.
Declaration:
Void textcolor(int newcolor)
Textbackground:
It selects a new text background color.
Declaration:
Void textbackground(int newcolor);
Value
Back-grd
BLACK
Yes
BLUE
GREEN
Yes
Yes
2
Fore-grnd
Yes
Yes
Yes
CYAN
Yes
RED
Yes
Yes
MAGENTA
Yes
Yes
BROWN
Yes
Yes
Yes
LIGHTGRAY
Yes
DARKGRAY
No
Yes
LIGHTBLUE
No
Yes
LIGHTGREEN
10
No
Yes
LIGHTCYAN
11
No
Yes
LIGHTRED
LIGHTMAGENTA
12
13
YELLOW
WHITE
BLINK
Yes
No
No
14
Yes
Yes
No
15
No
128
No
Yes
Yes
***
Page 45 of 86
***
To display blinking characters in textmode, add BLINK to the foreground
color.
If you want to display colors in textmode. We can use cprintf function.
Cprintf:
It is same as printf to print colored formatted data output.
Delay:
It suspends exectution for interval (milli seconds)
Declaration:
Void delay(unsigned milliseconds);
Kbhit:
It checks for currently available is keystrokes
Declaration:
Int kbhit();
Eg:
#include<stdio.h>
#include<conio.h>
Void main()
{
Int c=1,c1=36,r=1;
Textmode(1);
_setcursortype(_NOCURSOR);
While(!kbhit)
{
Textbackground(WHITE);
Clrscr();
Textcolor(BLUE);
Gotoxy(c,12);
Cprintf(RAJU);
Textcolor(GREEN);
Page 46 of 86
Gotoxy(c1,12);
Cprintf(RANI);
Textcolor(YELLOW);
Gotoxy(18,r);
Cprintf(WEDS);
C++;
C1++;
R++;
If(c>36)
{
C=1;
C1=36;
}
If(r>25)
{
R=1;
}
Delay(50);
}
}
100
_ _100(spaces before)
100_ _(spaces after)
Page 47 of 86
Printf(%.2d,n);
05
Char:
Char ch=h;
printf(%c,ch);
o/p:
printf(%4c,ch);
o/p:
_ _ _h(before 3 spaces)
printf(%-5c,ch); o/p:
h_ _ _ _(after 4 spaces)
Float:
Float ft=45.1352;
pritnf(%f,ft);
o/p:
45.135200
pritnf(%12f,ft);
o/p:
_ _ _45.135200
pritnf(%-12f,ft);
o/p:
45.135200_ _ _
pritnf(%.2f,ft);
o/p:
45.16
pritnf(%7.2f,ft);
o/p:
_ _45.16
printf(%s,st);
o/p:
welcome
printf(%9s,st);
o/p:
_ _welcome
printf(.3%s,st);
o/p:
wel
String:
Char st[10]=welcome;
Page 48 of 86
FUNCTIONS
A function is self contain block of statements and it performs a particular
task. It can be used at several times in a program but defined only once.
There are 2 types of functions are present. They are
1. Declaration
2. Definition
3. Calling
In case of predefined functions,
The function
The function
definition
The function
Calling
in Library files
in source program
Syntax:
Declaration:
Page 49 of 86
return_type
func_name([arg_list]);
Definition:
return_type
func_name([arg_list])
{
Body;
}
Calling:
func_name([parameter_list]);
Page 50 of 86
Exits immediately from the currently executing function to the calling
routine, optionally returning a value
Syntax:
return [<expression>];
Eg:
#include<stdio.h>
#include<conio.h>
Void main()
{
Int maxval(int,int); // declaration
Int a,b,m;
Clrscr();
Printf(Enter any 2 numbers : );
M=maxval(a,b);
Printf(maximum value : %d,m);
Getch():
}
Int maxval(int x,int y)
{
If(x>y)
Return x;
Else
Return y;
}
Page 51 of 86
Function with no arguments and no return type
Function with arguments and no return type
Function with arguments and with return type
Function with no arguments and with return type
Function with no arguments and no return type:
In this type the function has no arguments, it does not receive any data
from the calling function. Similarly it doesnt return any value from the calling
functions to the called function. So there is no data communication between
calling function and called function.
Function with arguments and no return type:
In this type the function has some arguments; it receive any data from the
calling function. But it doesnt return any value from the calling functions to the
called function. So there is one way data communication between calling
function and called function.
Function with arguments and with return type:
In this type the function has some arguments, it receives data from the
calling function. Similarly it returns a value to the calling function from calling
function. So there is 2 way data communication between calling function and the
called function.
Function with no arguments and with return type:
In this type the function has no arguments, it doesnt receive any data from
the calling function. but it returns a value from the calling function to the called
function. So here also only one way communication.
Page 52 of 86
STORAGE CLASSES
By the declaration statement the memory is allocated temporarily
for all the variables the size of memory varies with respect to the type
of the variable. The availability of the variable for access depends on
its declaration time.
The storage class specifiers are used to specify the life, scope of the
variables with in blocks, functions and the entire program.
There are 4 storage classes supports by c namely
Automatic variables:
These variables are declared inside a function block
Storage
main memory
Default value
garbage value
Scope
Life
:
which it is defined
Keyword
auto
Note:
If there no storage class specifies before the definition of any
variable inside a function block by default it takes auto storage class.
Static variables:
The memory of static variables remains unchanged until the end of
the program.
Storage
main memory
Default value
Scope
Life
:
that is local to a function, it allows the last value
of the variable to be preserved between successive calls to
that function.
Keyword
static
Page 53 of 86
Note:
In case of static variables the creation of static variable is done only
once, then its memory block is constant, in the execution of the
program.
main memory
Default value
Scope
global
Life
:
to end
Keyword
extern
Register variable:
We can use register variables for frequently used variables to
improve the faster execution of the program.
Storage
CPU registers
Default value
garbage value
Scope
Life
:
Till the control remains with in the block in
which it is defined
Keyword
register
Page 54 of 86
Note:
Recursion function:
Calling a function within the same function definition is called as recursive
function.
If you want work with recursive function we must follow the following 2
aspects
1. Calling by itself
2. Termination condition.
MATH.H FUNCTIONS
Sqrt:
It calculated square root of given number
Declaration: double sqrt(double x);
Pow:
It calculates exponential value of given base & power
Syntax:
Abs:
It returns an absolute value of given integer
Syntax:
Floor:
It rounds down the given value
Sytax:
ceil:
It rounds up the given value
Sytax:
Page 55 of 86
ARRAYS
Array is a collection or group of data elements of same data type stored in a
continuous memory location and it can be referred as a common name.
A particular value is indicated by writing a number is called INDEX or
SUBSCRIPT in square brasses after the array name.
Types of arrays:
c supports 3 types of arrays, namely
1. Single dimensional arrays or one dimensional arrays.
2. Two dimensional arrays or double dimensional arrays.
3. Multi Dimensional arrays.
Single dimensional arrays:
A group of data items can be given one variable name using only one index
such a variable is called as single dimensional array. In single dimensional arrays
the elements are represented one after the other in edges of memory bytes.
Declaration: data_type identifier[size];
Eg:
int a[5];
elements:
Initialization:
data_type identifier[size]={value-1,value-2,value (n-1)};
eg:
Page 56 of 86
int a[5]={1,2,3,4,5};
int arr[]={100,200,300};
STRINGS
A group of characters define between double quotations marks _ is a
string. It is a constant string. In c language a string variable nothing but an array
of characters and terminated by a null character[ \0].
Declaration: char identifier[size];
Eg: char st[80];
Initialization:
Syntax:
char identifier[size]=string;
puts:
it outputs a string to stdout(and appends a newline character).
declaration:
Page 57 of 86
Character functions:
getch:
it gets a character from console but doesnt but doesnt echo to the screen.
Declaration:
int getch();
getche:
it get a character from console and echoes to the screen.
Declaration:
int getche();
putchar:
it is a macro that outputs a character from stdout.
Declaration: int putchar(int c);
getchar:
it is a macro that gets a character from stdin.
Declaration: int getchar();
strcat:
Appends one string to another
Declaration:
char *strcat(char *dest, const char *src);
Remarks:
strcat appends a copy of src to the end of dest. The length of the
resulting string is strlen(dest) + strlen(src).
Return Value:
strcat returns a pointer to the concatenated strings.
String comparision:
Page 58 of 86
strcmp:
strcmp compare two strings
Declaration: int strcmp(const char *s1, const char*s2);
strcmpi:
strcmpi (a macro) compares two strings without case sensitivity
Declaration: int strcmpi(const char *s1, const char *s2);
stricmp:
stricmp compare two strings without case sensitivity
Declaration:
int stricmp(const char *s1, const char *s2);
Remarks:
The string comparison starts with the first character in each string and
continues with subsequent characters until the corresponding characters differ
or until the end of the strings is reached.
To use strcmpi, you must include STRING.H. This macro is provided for
compatibility with other C compilers.
Return Value:
These routines return an int value that is
< 0 if s1 < s2
== 0 if s1 == s2
> 0 if s1 > s2
Page 59 of 86
strcpy:
Copies string src to dest
Declaration:
char *strcpy(char *dest, const char *src);
Remarks:
Copies string src to dest, stopping after the terminating null character has
been moved.
Return Value: dest
strlen:
Calculates length of a string
Declaration:
size_t strlen(const char *s);
Remarks:
strlen calculates the length of s.
Return Value:
Returns the number of characters in s, not counting the terminating null
character.
String conversion:
strlwr:
Converts s to all lowercase
Declaration:
strupr:
Converts s to all uppercase
Declaration:
Remarks:
strlwr convert uppercase letters (A to Z) in string s to lowercase (a to z).
strupr convert lowercase letters (a to z) in string s to uppercase (A to Z).
Note: No other characters are changed.
Page 60 of 86
Return Value:
A pointer to the string s.
strrev:
Reverses all characters in s (except for the terminating null)
Declaration:
Remarks:
strrev changes all characters in a string to reverse order, except the
terminating null character.
For example, it would change
string\0 to
gnirts\0.
Return Value:
strrev returns a pointer to the reversed string.
a[0][1]
a[0][2]
Page 61 of 86
a[1][0]
a[1][1]
a[1][2]
Initialization:
Form 1:
Data_type arr_name[row_size][col_size]={val1,val2,val3.val-n};
Eg: int a[3][3]={1,2,3,4,5,6,7,8,9};
Form 2:
Data_type
arr_name[row_size][col_size]={{val1,val2,val3},{val1,val2,val3},
. {val1,val2,val3} };
Eg: int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};
int a[2][2][3];
Elements:
a[0][0][0]
a[0][0][1]
a[0][0][2]
a[0][1][0]
a[0][1][1]
a[0][1][2]
a[1][0][0]
a[1][0][1]
a[1][0][2]
a[1][1][0]
a[1][1][1]
a[1][1][2]
char st[5][20]
May be used to store a list of 5 strings eachof length not more than 20
charaters.
Page 62 of 86
POINTERS
Page 63 of 86
C provides the important feature of data manipulations with the address of
the variables. Hence the execution time is very much reduced. Such concept is
possible with the special data type is called Pointers.
DEF:
A pointer is a variable which stores address of another variable.
Declaration:
Pointer declaration is similar to normal variable declaration, but preceded by
*(Astrick).
data_type *identifier;
eg:
int *p1;
char *p2;
float *p3;
double *p4;
Initialization:
At the time of declaring a pointer we can store some address into the pointer
is called initialization.
Data_type *identifier=address;
Eg:
int n;
int *p=&n;
void *:
it is a generic pointer it refers the address of any type of variable and also it
assigns to any type of pointer.
Note:
Any type of pointer allocates only 2 bytes. Because it stores the address of
memory location.
Accessing pointers:
int n=100;
int *p=&n;
Page 64 of 86
-----Pointers and functions:
#include<stdio.h>
#include<conio.h>
Call by value
void main()
#include<stdio.h>
#include<conio.h>
void sum(int,int);
int a,b;
clrscr();
void main()
{
sum(a,b);
clrscr();
getch()
scanf(%d,&a,&b);
sum(&a,&b);
getch()
printf(sum is : %d ,x+y):
Page 65 of 86
void sum(int *x,int *y)
Call by reference
printf(sum is : %d ,*x+*y):
a[0]
0
a[1]
a[2]
a[3]
a[4]
Base address
The name a is defined as a constant pointer point into the first element a[0]
and therefore the value of a is 1000, the location where a[0] is stored that is a=
&a[0]=1000(base address.).
If we declared p as an integer pointer then we can make that pointer p to
point to the array a by the following assignment.
int *p;
p=a;
or p=&a[0];
Now we can access every value of a using p++ or p+1,p+2 to move one
element to another. The relationship between p and a is shown below.
p+0=&a[0]=1000;
p+1=&a[1]=1002;
p+2=&a[2]=1004;
p+3=&a[3]=1006;
p+4=&a[4]=1008;
When handling arrays instead of using array index, we can use pointer to
access array elements. Note that
*(p+k) use the value of a[k]
The pointer accessing method is much faster than array indexing.`
Dynamic memory allocation (DMA):C language requires the no. of elements in an array to be specified to
compile time but we maynot be able to do so always. Our initial judgment of size
if it is wrong, make cause failure of the program or wastage of memory space at
the situation we can use dynamic memory allocation.
Definition:
The process of allocation memory at runtime is known as dynamic memory
allocation.
Malloc:
It is used to allocate the memory at runtime declaration.
void * malloc(size_t size);
size_t:
type used for memory object sizes and repeat counts.
Usage:
Pointer=(type casting)malloc(memory size);
Eg:
int *p;
p=(int *)malloc(sizeof(int));
1 location.
p=(int *)malloc(5*sizeof(int));
5 location.
Note:
Malloc allocates specified no.of locations in the heap(RAM) and is initialize to
garbage values.
calloc:
It is used to allocate the memory at runtime declaration.
void *calloc(size_t nitems, size_t size);
Usage:
pointer=(type casting)calloc(no. of locations, memory size of each location);
Eg:
int *p;
p=i(int *)calloc(1,sizeof(int));
1 location.
p=i(int *)calloc(5,sizeof(int));
5 location.
Note:
calloc allocates a block (nitems * size) bytes and clears it to 0.
Free:
Frees allocated blocks
Declaration:
void free(void * block);
free de allocate a memory block allocated by a previous call to calloc,
malloc, or realloc.
Two dimensional pointer:
Int **a;
Allocation to the two dimensional pointer:
a =(int **)malloc(r*sizeof(int *));
allocation to the each row.
*(a+i)=(int *)malloc(c*sizeof(int));
Location
*(a+i)+j
Values
*(*(a+j)+j)
Realloc:
Reallocates at runtime.
Declaration: void *realloc(void *block,size_t size);
Realloc adjusts the size of the allocated block to size, copying the contents to
a new location.
STRUCTURES
Array is the collection of similar data types. But in case of records, the
occurrence of collection of different data types is takes place. So in case of
preparation of the records we use the structures.
C supports a constructed or derived data type, know as structure. This is a
method for packing data of different data types. A structure is a convenient tool
for handling a group of logically related data items. Structure helps to organize
complex data in a more meaningful way. It is powerful concept that we may often
need to use in our program design.
Struct:It is keyword and is used to define a structure.
Form1:
struct struct_name
{
Data_item 1;
Data_item 2:
------------------------------------------Data_item n;
};
Eg:
Struct emp
{
int eno;
char ename[25];
float sal;
};
Declaration of structure variable:
struct struct_name identifier;
Eg:
struct emp e;
Form -2 :
Declaration of struct, structure varaiable in a single statement.
struct struct_name
{
Data_item 1;
Data_item 2:
------------------------------------------Data_item n;
}var_list;
Eg:
struct emp
{
int eno;
char ename[25];
float sal;
}e;
. Access operator:
It is used to access the data items of a structure with the help of structure
variable.
struct_var.data_item;
eg:
e.eno;
e.ename;
e.sal;
Initialization of a structure:
Form1:
struct struct_name
{
Data_item 1;
Data_item 2:
------------------------------------------Data_item n;
};
Eg:
struct emp
{
int eno;
char ename[25];
float sal;
};
Declaration of structure variable:
struct struct_name identifier={val1,val2,val3..valn};
Eg:
struct emp e={100,hhh,10000.00};
Form -2 :
Declaration of struct, structure varaiable in a single statement.
struct struct_name
{
Data_item 1;
Data_item 2:
------------------------------------------Data_item n;
}var_list r={val1,val2,val3..valn};
Eg:
struct emp
{
int eno;
char ename[25];
float sal;
}e={100,hhh,10000.00};
Arrays of structures:
Like any other data type structure arrays can be of structure data type.
For example:
struct student s[100]; defines an array called s, that contains of 100
elements. Each element is defined to be the type struct student.
Pointers and structures:
A pointer can also point to a structure. For example
struct student
{
int sno;
char sname[20],course[20];
float fee;
};
struct student s;
struct student *p;
here p is defined to be a pointer pointing to student structure. We can write
p=&s;
After making such an assignment, we can access every no. of student
structure indirectly through p as follows
*p.sno;
*p.sname;
*p.course;
*p.fee;
Here instead of writing . and *.we can use the structure pointer operator
-> (arrow), which is the combination of (minus), >(greater than sign).
This means we can access every no.of student structure directly through p
as follows.
p->sno;
p->sname;
p->course;
p->fee;
Passing structure as function argument or function parameter:Like any other data type a structure may be used as function argument.
Syntax:
Eg:
disp(struct emp e);
Returning structure:
A function can not only receive structure as its argument but also can return
them.
Syntax:
struct_name fun_name();
Eg:
struct emp accept();
structure as both argument and also return type:
struct emp accept(struct emp e);
Nested Structure:
A structure with in a structure is called as structure with in structures is called as
nested structures.
Form 1:
Declaring a structure with in another structure is called as structure with in
structures.
struct student
{
int sno,c,cpp,unix;
char sname[20];
struct result
{
int tot;
float avg;
char res[10],div[10];
}r;
}s;
Accessing data:
s.sno; s.c;
s.cpp; s.unix;
s.r.div;
s.r.tot;
s.r.avg;
s.r.res;
It is a predefine structure and is and to get and set current system time.
struct time
{
unsigned char ti_min; /* minutes*/
unsigned char ti_hour;
/* hours*/
process.h; stdlib.h
System invokes the dos command interpreter file from inside an executing c
program to execute a dos command, bath file, or other program named by the
string command.
Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
system(cls);
system(date);
system(time);
system(dir);
getch();
}
Enum[Enumerated data type]:It is a used defined data type and is used to define a set of constants of type
int.
Enum[<type_tag>] {<const_nme> [=values],-----} [var_list];
Type_tag is an optional type tag that names the set.
Const_name is the name of a constant that can optionally be assigned the
value of <value>.
Note:
<value> must be integer. If <value> is missing, it is assumed to be
<prev>+1;
Where <prev> is the value of the previous integer constant in the
list. For the 1st integer constatnt in the list, the default value is zero.
<var_list>
Is an optional variable list that can follow the type declaration. It assigns
variables to the enum type.
Eg-1:
#include<stdio.h>
#include<conio.h>
enum{a,b,c,d};
void main()
{
clrscr();
printf(a= %d,a);
printf(b= %d,b);
printf(c= %d,c);
printf(d= %d,d);
getch();
}
Eg-2:
#include<stdio.h>
#include<conio.h>
enum boolean{false,true} b;
void main()
{
/* enum Boolean b; */
clrscr();
b=true;
printf(\nb=%d,b);
b=true;
printf(\nb=%d,b);
getch();
}
Eg-3:
#include<stdio.h>
#include<conio.h>
enum boolean{false,true};
void main()
{
int n;
enum boolean b;
clrscr();
printf(Enter any number : );
scanf(%d,&n);
b=iseven(n);
if(b==true)
printf(Given number is even);
else
printf(Given number is odd);
getch();
}
Typedef:It assigns the symbol name <identifier> to the data type definition <type
definition>.
Syntax:
Eg:
#include<stdio.h>
#include<conio.h>
typedef unsigned long ul;
void main()
{
ul n;
clrscr();
printf(Enter any number : );
scanf(%lu,&n);
printf(Given number : %lu,n);
getch();
}
FILES
c- language permits the usage of limited i/o functions to read and write data.
These functions are used for only small volumes of data and it becomes difficult
to handle longer data volumes also entire data is lost when the program is over
To overcome these difficulties a flexible method was developed by employing
the concept of files to store, to read or write and written them even the program
is over.
Def:
A file is one which enable the user to read, write and store a group of related
data.
Or
File is a collection of records stored in a particular area on the disk.
c supports a no.of functions to have the ability to perform the basic file
operations which includes.
1)
2)
3)
4)
Naming a file
Opening a file
Reading or Writing data from file
Closing a file.
FILE:It is a predefined structure and is used to declare a file pointer. Using this file
pointer, we can perform all file operations.
Dec:
FILE *identifier;
Eg:
FILE *fp;
Mode:-
Mode
Description
Open
an
existing
update(reading & writing)
w+
a+
file
for
Eg:
Fclose(fp);
Fcloseall:It closes all open file streams
Dec:
int
fcloseall();
EOF:
A constant indicating that end of file as been reached on file.
To get this charater from keyboard press ctrl+z.
getc:
Getc is a macro that gets one character from a file stream.
Dec:
putc:
fgetc:
fgetc that gets one character from a file stream.
Dec:
fputc:
fputc outputs one character to a stream.
Dec:
Rewind:
It repositions file pointer to a file streams beginning.
Dec:
It reads characters from a file stream into the string s, it stops when it reads
either n-1, character or a new line character, which ever comes first.
Fputs(), it copies the null terminated string s to the given output file stream.
It does not append a newline character, and the terminating null character is not
copied.
Feof():
It is a macro that tests if end of file has been reached on a file stream.
Dec:
Return value:
Note:
If fprintf, fscanf between formats atleast one space is nessecary.
BINARY FILES
Getw:It gets an integer from a file stream.
Dec:
Fwrite:
It appends a specified number for equal sized data blocks into an output file.
Dec:
Fread:
It reads a specified number of equal sized data blocks from an input file
stream into a block.
Dec:
Arguments:
Ptr
Size
stream
Fseek:
It repostions the file pointer of a file stream.
Dec:
Argument:
Stream:
Offset:
When:
COMMAND LINES
We know that every c- program should have one main function and it can
take arguments like other functions. If you want to work with command line
arguments the main function can take 2 arguments call argc, argv and the
information contain in the command line is processed on to the program through
these arguments.
file_name arguments
:/> my_args aa bb cc dd