Sie sind auf Seite 1von 86

Page 1 of 86

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.

What output to be desired?


What are the inputs?
How to be processed?

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.

Computer memory origination:

Parts of Computers:
Mainly 2 parts are exit in computers one is HARDWARE(H/W) and
SOFTWARE(S/W).
What
o
What
o

you touch physically is hardware?


H/W is the collection of electronic and mechanical devices .
you cant touch physically is software?
S/W is the collection of programs.

Hardware:

All the physical components or units connected to the computer


circuit is known as 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

Analysis and Design Phase

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

Nature of the problem

Programming language available on the computer system.

Limitations of computer

Debugging and Testing:


Before loading the program in to the computer, we must locate and
correct all the errors. The process of correcting errors in a program is called as
debugging. There are 3 types of errors that generally occur in a program namely
o

Syntax errors

Logical errors

Runtime errors

It is very important to test the program written to achieve a specific task


data of which the result are known as the results are known the results produced
by the compute r can be verified.
Documentation:

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

Classes and objects

Logic Oriented

Goals often expressed in predicate calculus

Rule Oriented

If then and else rules

Constraint Oriented

Invariant relationship

There are 3 types of paradigms are preset. They are

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

Eg: FORTRAN AND COBOL

Page 9 of 86

Glob
al
Data

Sub
Progr
ams
Structured Programming:

Emphasis on algorithm rather than data.


Programs are divided into individual procedures that perform discrete
tasks.
Procedures are independent of each other as far as possible and have
their own local data and processing logic.
Controlled scope of data
Introduction of the concepts of user defined data types
Support for modular programming, Large projects are bfoken up into
modules and programmed independently.

Eg: Pascal and C

Page 10 of 86

Global
Data

Modul
e1

Modul
e2
Sub
Programs

Modul
e3

Object Oriented Programming:

Emphasis on data rather than algorithm


Data abstraction is introduced in addition to procedural abstraction
Data and associated operations are unified into a single unit, thus the
objects are grouped with common attributes, operations and semantics
Programs are designed around the data being operated, rather than
operations themselves.
Relation ships can be created between similar, yet distinct data types.

Page 11 of 86

Object
A

Object
B

Object
B

History of the Programming Languages:


Era
1960s

Applications

Major languages

Other languages

Business

COBOL

Assembler

Scientific

FORTRAN

ALGOL, BASIC

System

Assembler

JOVIAL,FORTH

AI

LISP

SNOBOL

Business

COBOL, C++, Java,


Spreadsheet

C, PL/I, 4GLs

Scientific

FORTRAN, C, C++,
Java

BASIC

Today

Page 12 of 86
System

C, C++, Java

Ada, BASIC, Modula


AI

LISP, Prolog

Publishing

TeX, Postscript, word


processing

Process

UNIX shell, TCL, Perl,


JavaScript

AWK, Marvel, SED

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.

Basic structure of C Language program:


[Document Section]
Pre-Processor Section or Link Section
[Global declaration Section]
Main()
{
[Local Declaration Section]

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.

Link Section (or) Preprocessor Section:

It provides instructions to the compiler to link the functions from the


System Library.

Global Declaration Section:

The variables that are used in more than one function are called global
variables and these variables are called in the Global Declaration Section.

Main Function 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.

Sub Programming Section:


It consist all the user defined function. This section may be placed before
or after the main function.

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.

#include file name


#include <file name>
When the file name is included with in double quotation marks( ). The
search for the file is made first the current directory and then standard directory,
otherwise when the filename included with in < > brasses the file is searched
only in the standard directory.

Page 17 of 86

Stdio.h ---- standard input output header file.


Conio.h ---- Console input output header file.
Console units keyboard , monitor.
Note:
These 2 headers are used commonly in c program

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.

General languages 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.

There are 32 reserved key words are present in c- language. In ANSI C


there are some more keywords are present.
Ex:
Auto, double, long, struct, union, void.

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();

Rules to write variable names or Identifiers:

A variable name contains maximum of 30 characters.


A variable name includes alphabets and numbers, but it must start with an
alphabet.
It cannot accept any special characters, blank spaces except under
score( _ ).
It should not be a reserved word(keyword).
Variables:Variables are those whose value varies(changes) at the time of program
execution. i.e. value in the memory block doesnt changes.

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:-

Strings means nothing collection of the Characters. In C there is no


direct definition for string type. But an array of characters is known as String.

Page 21 of 86
Syntax:
char string_name[ size ];
ex:
char st[25];

Operators:

It is a symbol and it performs a particular operation. Operant is an entity


on which an operator acts. C has a rich set of operators.
1.
2.
3.
4.

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:-

The kind of data that variables may hold in programming language is


called as data types.

Page 22 of 86

Data types are of 3 data types.


1.
2.
3.

Primary Data Types


Derived Data Types
User Defined Data Types

Primary Data Types:

All C compliers supports


int,char,float,double.

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

Derived Data Types:

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.

User Defined Data Types:


The user define data types enable a program to invent his own data types
and defined what values it can taken. Thus this data types can help reducing the
programming errors.
In C language 2 types of user define data types are available namely.

Typedef(Type definition)
ENUM (Enumerated data type)

Type modifiers or type qualifiers (signed, unsigned, short and long) :

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

Memory Size (in


bytes)

Accessibility Range

unsigned char

%c

0 to 255

char

%c

-128..0.127

int

%d

-32768 to -32767

unsigned int

%u

0 to 65535

long (or) long int

%ld

-214783548 to 214783647

unsigned long
(or) unsigned
long int

%lu

0 to 4294967295

float

%f

3.4 *(10**-38) to 3.4*(10**38)

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():

It is a function and is used to print data on the standard output device.


Declaration:
int printf(Control string[,arg1,arg2,arg3]);
eg:

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.

Steps to Entering into c editor


1. Double click on desktop turboc++ icon or startmenu-> run>c:\tc\bin\tc.exe and enter.
2. check path
options menu->directories -> 1)c:\tc\include
2)c:\tc\lib
3)----4)----Note:
It is for if you install the turboc++ software. If not so plz check path c:\tc.
3.
4.
5.
6.
7.
8.
9.

open file menu(alt+f)


select new-> type c program
save file f2 or alt+f+c
compile {compile menu select compile option}
run {run menu select run option}
output {window menu select users screen}
quit {file menu select quit option}

Shortcut keys for c editor:

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.

Escape Sequence Characters:

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();
}

Data reading from key board:


Scanf:
It is a function and is used to read data from standard input device.
Syntax:
int scanf(format(s),address-1,adress-2.);
Eg:
int n;
scanf(%d,&n);

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.

C operators can be classified into a no.of categories. They are

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

<=

Less than or equal to

>

Greater than

>=

Greater than or equal to

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

- Logical AND true only all conditions are true


-

Logical OR true if any one or both of the conditions are

- Logical NOT Inverse of the statements

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);

Control structures or statements


-------------------------------------c is a considered as a structured programming language one of the reason
for this is

having varios program control statements C process the decision making


capabilities and supports
the statements known as control statements C supports three types of control
statements they

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

ignored.otherwise expression is false then else block statement is executed and


if block

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.

Loop control statements

The process of repeatedly executing a block of statements up to specify


no. of times is called as loop.
Every loop has 3 parts

Initialization --- start


Test condition --- condition
Change the index --- end

C supports 3 types of looping statements. They are


1) While loop
2) Do_while loop
3) For loop
While loop:
It is a conditional control loop statement in c language.
Syntax:
While(test condition)
{

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 Window Formattings


Text Mode:
It changes screen mode.
Declaration:
Void textmode(int newmode);

Text modes:Constant

value

TextMode

Lastmode

-1

previous text mode

BW40

black & white

C40

color

BW80

black & white

C80

color

80 cols

MONO

Monochrome

43 lines

C4350

64

EGA AND VGA

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

(solid block cursor)

_NORMALCURSOR (normal underscore cursor)

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);

COLORS (text mode):


Constant

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);
}
}

FORMATTING THE OUTPUT


Int:
Int n=100;
Printf(%d,n);
Printf(%5d,n);
Printf(%d,n);
Int n=5;

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. Library functions or Predefined Functions.


2. User Defined Functions.
Predefined Functions or Library Functions:
The function, which are in built with the compiler are called as library
functions.
User Defined Functions:
User can be defined functions to do at task relevant to their programs,
such functions are called as User Defined Functions.

Any functions has three parts.

1. Declaration
2. Definition
3. Calling
In case of predefined functions,
The function

declaration in header files

The function

definition

The function

Calling

in Library files
in source program

But in case of user defined functions


All the 3 things are in your 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]);

The arguments which are given at the time of function declaration or


definition are called as formal arguments given at the time of function calling
are called as actual arguments or parameters.
Rules for creating and accessing user defined functions:

1. A function can be called by any no.of times


2. A function may or may not return a value.
3. If a function does not return any value, the function declaration data
type will be specified as void
4. If a function returns a value only one value can be return.
5. We cant specify any return data, the function returns an integer
value by default.
6. If a function returns a value the returning value must be returns with
a statement.
7. If a function returns a value the execution of return statement
should be lost.
8. If a function returns a value the returning value should match with
the function return type.
9. A function is executed when the function is called by its name.
10.
A function may or may not receive arguments.
11.
Before a function call function declaration or definition is must
and should
12.
A function definition may be placed before or after the main
function
13.
If a function declaration is specified before function call then
the function defined anywhere in the function(before or after main
function).
14.
If a function is defined before the function call then the
function declaration is not necessary.
15.
The function should not be terminated by ;
Return :

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;
}

Category of functions or function prototypes:


A function depending on whether arguments are present or not and
whether a value is returned or not may belongs to one of the following
categories.

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

local to the block in which it is defined

Life
:
which it is defined
Keyword

Till the control remains with in the block in

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

0(in case char null character (ascii value 0)

Scope

local to the block in which it is defined

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.

External or global variables:


Variables that are both alive and active through out the entire
program are known as external variables.
Storage

main memory

Default value

0(in case char null character (ascii value 0)

Scope

global

Life

:
to end

Keyword

as long as the program execution doesnt come

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

local to the block in which it is defined

Life

:
Till the control remains with in the block in
which it is defined

Keyword

register

Page 54 of 86
Note:

These variables are declared inside function block only

It supports only integral data types (int &char)

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:

double pow(double x, double y);

Abs:
It returns an absolute value of given integer
Syntax:

int abs(int x);

Floor:
It rounds down the given value
Sytax:

double floor(double x);

ceil:
It rounds up the given value
Sytax:

double ceil(double x);

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:

a[0],a[1] ,a[2] ,a[3] ,a[4]

Note: in any array the array index is from 0 to size-1.

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;

Note: here size is optional.


Eg:
char st[10]=welcome;
char st[]=abcd;

the compiler assigns a character string to a character array, it automatically


supplies a null character(\0) at the end of a string.
Therefore the size should be equal to the maximum no. of characters in the
string+1.
Format specifier of string is %s.
String functions:
gets:
it gets a string from stdin
declaration:

char *gets(char *s);

puts:
it outputs a string to stdout(and appends a newline character).
declaration:

int puts(char *s);

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();

String handling functions:

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:

strcmp performs an unsigned comparison of s1 to s2.

strcmpi (implemented as a macro that calls stricmp) performs an unsigned


comparison of s1 to s2, without case sensitivity.

stricmp performs an unsigned comparison of s1 to s2, without case


sensitivity.

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:

char *strlwr(char *s);

strupr:
Converts s to all uppercase
Declaration:

char *strupr(char *s);

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:

char *strrev(char *s);

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.

TWO DIMENSIONAL ARRAYS


A Two dimensional array can store a table of values which contains rows and
columns. In 2 dimensional arrays we can use 2 index values
The first index for rows and second index for columns.
The general form of 2 dimensional array is
data_type arr_name[row_size][col_size];
Eg:
int a[2][3]
elements:
a[0][0]

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}};

MULTI DIMENSIONAL ARRAYS


c supports arrays of 3 or more dimensions in multi dimensional arrays. We
use more than two index values. The general form of multi dimensional array is
Declaration: data_type arr_name[s1] [s2] [s3] . [sn];
Eg:

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]

TWO DIMENSIONAL ARRAYS


A list of names can be treated as table of strings and a two dimensional
character arrsy can be used to store the entire list
Eg:

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:

Parameter passing techniques or calling mechanism of argument functions.


Calling by value:
The process of passing the value to the function called is known as call by
vlaue
Calling by reference
When we pass address to a function, the parameters receiving the address
should be pointers. The process of calling a function using pointers to pass the
address of variable is known as call by reference.
The function which call by reference can change the value of the variable
used in the call.

#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()
{

printf(Enter any 2 values : );


scanf(%d,&a,&b);

void sum(int *,int *);


int a,b;

sum(a,b);

clrscr();

getch()

printf(Enter any 2 values : );

scanf(%d,&a,&b);

void sum(int x,int y)

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):

Arrays and Pointers:


When an array is declared, the compiler allocates a base address and
sufficient amount of storage to contain the all elements of an array in continues
memory allocation. The base address location of first element(index=0) of the
array. The compiler also defines the array name as a constant pointer to the first
element.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5];
clrscr();
printf(Base address : %x,&a[0]);
printf(Base address : %x,a);
getch();
}

Suppose we declare an array as follows


int a[5]={1,2,3,4,5};
Suppose the base address of a is 1000 and assuming that each integer
requires 2 bytes, the 5 elements will be stored as follows.
Elements
Values
address

a[0]
0

a[1]

a[2]

a[3]

a[4]

1000 1002 1004 1006 1008

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:

ret_type fun_name(struct struct_name var);

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;

Dos.h header files


Time :-

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*/

unsigned char ti_sec; /* seconds*/


};

gettime:It gets current system time


Syntax:

void gettime(struct time *t);

settime:It sets current system time


Syntax:

void settime(struct time *t);

Note: These functions get and set only 24 hours time.


#include<stdio.h>
#include<conio.h>
#include<dos.h>
void main()
{
struct time t;
clrscr();
gettime(&t);
printf(Current system time: %.2d : %.2d :%.2d\n,t.ti_hour,t.ti_min,t.ti_sec);
getch();
}

To change the system time:#include<stdio.h>


#include<conio.h>
{
struct time t;
int h,m,s;
clrscr();
gettime(&t);
printf(current system time : %.2d : %.2d :%.2d\n,t.ti_hour,t.ti_min,t.ti_sec);
printf(\n Enter new time (hh:mm:ss) : );
scanf(%d:%d:%d,&h,&m,&s);
t.ti_hour=h;
t.ti_min=m;
t.ti_sec=s;
settime(&t);
printf(System time is changed );
getch();
}
System:-

process.h; stdlib.h

It issues a dos command.


Syntax:

int system(const char *command);

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};

enum boolean iseven(int x)


{
If(x%2==0)
return true;
else
return false;
}

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:

typedef <type dfination> <identifier>;

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;

Files are of 2 types text or sequential file, binary file.


Text File (or Sequential file):For reading and writing data in continuous blocks in this files the information
is represented instead of characters. The size each and every character is 1 byte.
Binary Filels:For Reading and writing data orbiter structured files. In this files the
information. In this files the information is represented instead of data block. The
size of data block depend on its data type.
Fopen:It opens a file stream
Dec :- FILE * fopen(const char *file_name,const char *mode);
Filename:

file that the function opens.

Mode:-

Mode

Description

Opens for reading only

Create for writing. If a file by that name


already exists, it will be over written.

Append. Open for writing at end of file,

or create for writing if the file doesnt


exist.
r+

Open
an
existing
update(reading & writing)

w+

Create a new file for update(reading &


writing). If a file by that name already
exists it will be over written.

a+

Open for append; Open for update at


the end of file or create if the file
doesnt exist.

file

for

To specify that the given file is being opened or created in text


mode, append t to the string.(rt,w+t etc).
To specify that the given file is being opened or created in binary
mode, append b to the string.(rb,w+b etc).

Fclose:It closes a file stream.


Dec:

int flcose(FILE *stream);

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:

int getc(FILE *stream);

putc is a macro that outputs one character to a stream.


Dec:

int getc(FILE *stream);

fgetc:
fgetc that gets one character from a file stream.
Dec:

int getc(FILE *stream);

fputc:
fputc outputs one character to a stream.
Dec:

int getc(FILE *stream);

Rewind:
It repositions file pointer to a file streams beginning.
Dec:

void rewind(FILE *stream);

Fgets:It gets a string from a file stream


Dec:

char *fgets(char *s, int n, FILE *stream);

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 outputs a string to a file stream.


Dec:

char *fputs(char *s, FILE *stream);

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:

int feof(FILE *stream);

Return value:

o Returns non-zero if an end of file indicator was detected on


the last inputopeartion on the same stream.
o Returns 0 if endof file has not been reached.
Fprintf:
It sends formatted output to a file stream
Dec:- int fprint(FILE *stream,const char *format[,argumens,);
Fscanf:It scans and formats input from a file stream.
Dec:

int fscanf(FILE *stream,const char *format[,address,..]);

Note:
If fprintf, fscanf between formats atleast one space is nessecary.

BINARY FILES
Getw:It gets an integer from a file stream.
Dec:

int getw(FILE *stream);

Putw:It outputs an integer on a file stream.


Dec:

int puw(int w,FILE *stream);

Fwrite:
It appends a specified number for equal sized data blocks into an output file.
Dec:
Fread:

size_t fwrite(void *ptr, size_t size,size_t n, FILE *stream);

It reads a specified number of equal sized data blocks from an input file
stream into a block.
Dec:

sizd_t fread(void *ptr,size_t size, size_t n, FILE *stream);

Arguments:
Ptr

points to a block into which data is write/read.

Size

length of each item write/read in bytes.

number of items write/ read

stream

points to output(input file stream);

ftell:it returns the current file pointer position.


Dec:

long ftell(FILE *stream);

Fseek:
It repostions the file pointer of a file stream.
Dec:

int fseek(FILE *stream, long offset, int when);

Argument:
Stream:
Offset:
When:

stream whose file pointer fseek sets


difference in bytes between when and new position
one of the seek-XX file pointe locations(0,1,2).

COMMAND LINES

It is a parameter supplied to a program when the program int invoked. This


parameter may represented a file name, the program should process command
line arguments are typed by the used. The first argument is always the file name.

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.

The variable argc(arg counter) is an argument counter that counts to the


no.of arguments on the command line. The argv is an argument vector and
represents an array will be equal to the value of argc.
Eg:
/* my_args.c */
#include<stdio.h>
#include<conio.h>
void main(int argc,char *afgv[])
{
int I;
printf(no.of arguments : %d,argc);
for(i=0;i<argc;i++)
printf(\n arguments %d : %s ,i,argv[i]);
getch();
}
Note: press f9 to save file.
Then go to dos shell, then run the file as
Dec:

file_name arguments

:/> my_args aa bb cc dd

Das könnte Ihnen auch gefallen