Vous êtes sur la page 1sur 27

INTRODUCTION

Computer is a modern electronic device that accepts input data, do processing


according to a set of instructions, called program and produce/store the output
Information. The term computer has been derived from the word COMPUTE.
First digital computer was ENIAC (Electronic Numerical Integrator And
Computer).Father of computers Charless Babbage.
DATA: It represents raw facts and observation. Ex: number, word, amount, holiday
etc.
INFORMATION: It is the result of processing of the data. That means the data that
has been transformed in useful and meaningful form is known as information. Ex: I
am an Indian is information which conveys some meaning to us.
In the simplest form, we can say a computer is combination of software and
hardware.
Software: It is the set of instructions (called program) written for a computer to
perform a particular task. Generally software is written in any one of the computer
languages like C, C++, Java, COBOL, etc. Broadly software can be classified as 2
types.
1) System Software: It refers to a collection of software such as compilers,
operating systems, etc. which provides vital services to the users and makes
the computer user friendly.
2) Application Software: It refers to the programs usually used by users for
performing their desired tasks. Ex: MS-Office, Audio/Video players, Calculator,
Image editing software etc.
Hardware: It refers to the physical components of a computer system. Ex: Processor,
keyboard, mouse, hard disk, printer, monitor etc.
Reasons to use Computer:
Storage
Speed
Accuracy
Multitasking
Networking & File sharing

Security etc

PROGRAM DEVELOPMENT STEPS:


The process of achieving the required level of satisfactory details is
called problem analysis.
There are 7 steps.
1) Problem specification
2) Outlining the solution
3) Representing algorithm
4) Flowchart
5) Removing errors
The process of detecting and correcting errors is called debugging (bug means
program error). There are 3 types of errors.
(i)

Syntax errors: The grammatical rules, which govern programming languages, are
called as syntax.
Ex: wrongly typed statements like missing semicolon, spelling mistakes etc.

Computer can detect these errors at compile time.


(ii) Run-time errors: Errors detected at the time of program execution are called
run-time errors.
Ex:

a) Dividing by zero
b) Square root of a negative number
c) Logarithm of a negative number
d) Mixing of various data types

(ii)

Logical errors: Logical errors are due to the existence of logically incorrect
instruction in the program. These errors can be known only after output is
examined. Logical errors are often hard to find even when they are known to
exist.
6) Testing
7) Document and maintenance
Documentation is process of collecting, organizing and maintaining
complete information about the program.
Modifications of the program according to the user requirement are

called program maintenance.


ALGORITHM:

It is a method of representing the step-by-step logical procedure for solving a


problem.
FLOWCHART:
Flowchart is a graphical representation of an algorithm.

Oval

Terminal

Start / Stop

Making
Parallelogram

Input / output

for

data available
processing

recording

of

or
the

processed information
An assignment operation
Rectangle

Process

normally represented by
this symbol.

Diamond

Decision

Ex: a>b, a!=b etc

Used
Circle

Connector

different

to

connect
parts

of

flowchart.
Joins two symbols and
Arrow

Flow

also represents flow of


execution

Bracket with

Annotation

broken line

Descriptive comments

Double sided

Predefined

rectangle

process

Modules or subroutines

INTRODUCTION TO C:
It was developed in the 1970s by Dennis M. Ritche at Bell Telephone
Laboratories (AT & T Bell Labs). C is an outgrowth of BCPL (Basic Combined
Programming Language) developed by Martin Richards at Cambridge University.
BCPL also called as B language.
C is a middle-level computer programming language, because it has the
features of both high-level languages, such as ADA, C++, JAVA, FORTAN, COBOL,
ALGOL, BASIC, PASCAL etc., and low-level languages such as assembly language,
Machine-level languages.
C FEATURES:
1) C has very small instruction set. Just we have only 32 keywords in C.
2) C is portable i.e., software written for computer can be run on another
computer.
3) We can add user defined functions to C library.
4) C is modular.
5) C is robust.
ADVANTAGES OF C:
1) C programs take less memory than other languages.
2) C programs runs faster than all other languages.
APPLICATIONS OF C:
1) To develop 2D, 3D games
2) To develop Operating Systems like DOS, WINDOWS, UNIX, LINUX,
MACINTOSH etc. The entire UNIX OS developed in C.
3) Programs for device drivers

4) Programs for consumer electronic devices such as refrigerator, digital


camera etc.
5) To develop all system and application software
6) In mobile devices and palmtops etc.

STRUCTURE OF A C PROGRAM:
Documentation section
Global declaration section
Preprocessor section
Main ( )
{
Declaration part;
Executable part;
- - - - - - - - - - - - - - - - - - - - - }
Sub Function section

Ex: /* FIRST PRGORAM IN WRITTEN BY B.RAVINDER

DATE: 2-12-2006

*/

# include<stdio.h>
Void main ( )
{
printf (HEARTLY WELCOME TO C LEARNERS);
}
Comments in the C program are optional and may appear anywhere in a C
program.
Comments are enclosed between /* and */.
Comments can not be nested.
Comments are used to write to tell information about a program like
programmer name, program name, date etc.
All comments are ignored by the compiler.

The execution of the C program starts from main and executes all instructions
sequentially. The word main is followed by a pair of ordinary parenthesis ( ), which
indicates that main is a function.

RULES TO WRITE C PROGRAMS:


1) All C statements must end with semicolon.
2) C is case-sensitive. That is, upper and lower case characters are different.
Generally the statements are typed in lower case.
3) A C statement can be written in one line or it can split into multiple lines. So
C called as a Free-form language.
4) Every open brace {must have a matching close brace}.
5) Comments can not be nested.
6) A comment can be split into more than one line.
EXECUTION OF A C PROGRAM:
1) Open C editor. FILE menu--->NEW
2) Type a program. FILE menu--->SAVE
3) COMPILE menu--->COMPILE or press Alt+F9
4) RUN menu--->RUN or press ctrl+F9
IN UNIX:
$ CC filename.c ------------ Compile
After successful compilation it produces an executable file a.out.
$ a.out

-------- Run

STEPS IN LARNING C and Other Languages:


In general any language follows like

Alphabets
Nested IF:

Words

Sentences

Paragraph

IN C
Alphabets
,l
(A-Z, a-z),
Digits (0-9),
Special symbols

Constants,
Variables,
Keywords

Statements,
Sub functions

Programs
Software

* ^ & @ ! ~ + ( [ etc

A constant is a literal, which remain unchanged during the execution of a


program.
In C, integer constants can also be written in octal and hexadecimal number
systems.
0464 Octal (write 0 before number)
0X2BD Hex (write 0x or 0X before number)

A variable is a name that is used to store data value and is allowed to vary the
value during the program execution.
Ex: int x=10; //here int is data type x is a variable, 10 is constant and =, ; are special
characters.
Rules for constructing variable names:
1) The first character must be either underscore (_), or a letter.
2) No special characters permitted except underscore.
3) Blanks are not allowed with in a variable name.
4) Upper case and lower case letters are not same.
5) The variable name should not be a C keyword.
6) The variable name should not be a user defined or library function name.
To declare a variable syntax is: data-type var-name;
Ex: int x, y, z;
A digit, or an alphabet, or a special symbol enclosed in a single quote is called
a character. Ex: 9, a,#. Every character contains its equivalent ASCII
(American Standard Code for Information Interchange) value.
Group of alphanumeric characters enclosed with in the double quotes is called
a string. To identify the end of the string every string in C ends with a null
character (\0). Ex: 9, abc123, hello, +-*//+
Note: 9, 9, 9 are not same.

Keywords are predefined tokens in C. token is a character or group of


characters recognized by a compiler. Keywords are also called as reserved
words. We have 32 keywords according to the ANSI (American national
Standard Institute) C. They are
1) auto

9) double

17) int

25) struct

2) break

10) else

18) long

26) switch

3) case

11) enum

19) register

27) typedef

4) char

12) extern

20) return

28) union

5) const

13) float

21) short

29) unsigned

6) continue

14) for

22) signed

30) void

7) default

15) goto

23) sizeof

31) volatile

8) do

16) if

24) static

32) while

DATA TYPES:
A datatype defines a set of values and the operations that can be performed on
them. They are 3 types.
1) Primary (Basic) -------- int, char, float, double, void
2) Derived ------------------array, structure, union, pointer
3) User defined ----------- typedef, enum
Size in

Format

bytes

Specifier

signed char

%c

-128 to 127

unsigned char

%c

0 to 255

signed int

%d or %u

unsigned int

%u

0 to 65535

signed short int

%d

-32768 to 32767

unsigned short int

%d

0 to 65535

signed long int

%ld

-2147483648 to 2147483647

unsigned long int

%ud

0 to 4294967295

float

%f

3.4E-38 to 3.4E+38

double

%lf

1.7-308 to 1.7E+308

Type- keyword

Range

-32768 to 32767

long double

10

%Lf

3.4E-4932 to 1.1E+4932

Note: default is signed.


INPUT AND OUTPUT STATEMENTS:
Printf( ): It is a C built-in function used to write information to standard output devices.
Syntax:

1) printf(string);
2) printf( format string, list of variables);
printf(WELCOME TO C WORLD);

Ex:

printf(a=%d b=%d and sum=%d, a, b, a+b);


printf( ) returns the number of characters written, or in case of error, it returns a
negative number.
Scanf( ): It is a C built-in function that allows a program to get user input from the
keyboard.
Syntax: scanf( format string, address of lost of variables);
Ex:

scanf(%d%f, &d, &f);

Scanf() returns number of items read and stored, in case of any error it returns
-1.
Note: C is not a strongly typed programming language. That is in C even you assign
integer value to float variable or float value to character variable compiler does not
show any error. Examples for strongly typed programming languages are Java,
COBOL etc.
C, C++, Java are free form languages. That means you can write a same single
statement in multiple lines.
OPERATORS & EXPRESSIONS:
Operator: It is a symbol that tells the computer to perform certain mathematical
or logical manipulations.
Expression: It is a combination of constants, variables and operators produce a
single value after evaluation.2 types of expressions are
1) Numerical Expressions: which gives numerical value
Ex: 2, 2+3, 2/a, a*b, (x+y)*c+5 etc
2) Boolean expressions: which return true or false

Ex: a>b, a<b, a! =b, a==b etc


Types of operators:
1) Relational operators : >, <, <=, >=, = =, ! =
2) Arithmetic operators : +, -, *, /, %
3) Bitwise operators : &,, ~, >>, <<
4) Logical operators: &&, , !
5) Increment / decrement operators: + +, - 6) Assignment operators: +=, -=, *=, /=, %=
7) Conditional operators: ?, :
8) Special operators: sizeof( ), period(.),

Precedence of Operators:
OPERATOR

ASSOCIATIVITY

RANK

( ), [ ], ->

Left to Right

!, ~ ++, - -, *, &, sizeof()

Right to Left

*, /, %

Left to Right

+, -

<<, >>

<, <=, >, >=

= =, !=

&

10

&&

11

||

12

?:

Right to Left

13

14

=, +=, -=, *=, %=, /=


10

Left to Right

15

TYPE CONVERSION:
The process of converting one data type to another data type is called a type
conversion. The value of the right side of the assignment operator (rvalue) is
converted to the type of the left side variable (lvalue).
Ex:

int i;
float f;
i=8.25;
f=10;

After conversion I value is 8 and f value is 10.000000


DECESION CONTROL STRUCTURES:
1) if

2) switch

Types of If are 1) if
if syntax:

3) goto

2) if-else

if (expression)
{
statement-1;
statement-2;
-------------statement-n;
}

3) else-if ladder
if-else syntax:

4) nested-if

if (expression)
{
statement-1;
statement-2;
-------------statement-n;
}
else
{
statements;
}

else-if ladder syntax:


if (condition1)
{
statement-1;
--------------------------------}
else if (conditon2)
{
--------------------------------}
else if (condition3)
{

--------------------------------}
nested-if Syntax: If (condition)
{
If (condition)
{
11

statement-1;
statement-2;
--------------

statement-n;
}
}

For simple if if that given condition is true then it executes if statements.


For if-else if that given condition is true then it executes the if statements otherwise
it executes the else statements,.
If there are more conditions then it is better to use else-if ladder.
For nested if if the first condition is true then it checks the second condition. If the
second condition also true then only it executes the statements.
GOTO: A goto is an unconditional jump statement. It jumps to a position indicated by
label.
Syntax:

label-name: statement-1;
statement-2;
-------------statement-3;

goto label-name;
** GOTO may be after or before the label name.
SWITCH:
The switch makes one selection when there are several choices to be made.
Syntax: switch (integer expression)
{
case casevalue-1: statement-1;
--------------;
statement-n;
break;
case casevalue-2: statement-1;
--------------;
statement-n;
break;
case casevalue-n: statement-1;
--------------;
statement-n;
break;
default:
statement-1;
--------------;
statement-n;
break;
}

12

For the casevalue we can write either an integer or a character but not float and
string.
Each casevalue must be distinct.
The break causes an immediate exit from the switch. If the break is not
included, all of the statements below the match will be executed.
When integer expression matches with casevalue, compiler executes the
statements following that case.
If the break statement is not included, all of the statements below the match will
be executed.
If no match is found with any one of the case statement then the default
statements will be executed.

LOOPS: A portion of program that is executed repeatedly is called a loop.


Loops are useful when you want to execute one or more instructions more than one
time. We have 3 types.
1) while

2) do-while

3) for

Syntax:
initialization;

do

while( expression)

for(initial; exp; inc / dec)


{

statement-1;

statement-1;

statement-1;

statement-2;

statement-2;

statement-2;

----------------

----------------

----------------

statement-n;

statement-n;

statement-n;
increment / decrement;
}

increment / decrement;

}
while(expression);

In while first if the condition is true then only compiler executes the while
statements. If condition is false then compiler executes the next instruction
which is after the close brace of while. So while is called an entry-control loop.
In do-while first compiler executes the instructions then it checks the condition.
If that condition is false it goes to the next instruction which is after the close
brace of while. So it is called an entry-control loop.
The main difference between while and do-while is in while if the condition is
false compiler does not executes instruction. Where as in do-while even
condition is false compiler executes the instructions at least once.

13

The advantage with for is we can write initialization, condition and increment /
decrement parts in a single statement.
In for loop any or all of the 3 sections in the parentheses can be omitted,
although the semicolons must remain. If the conditional expression is assumed
to have a value 1 and the loop continues infinitely.
for ( ; ; )
{
statement-1;
---------------statement-n;
}
C allows nested loops i.e., a loop with in a loop.
One or more statements enclosed with in the open brace( { ) and close brace
( } ) is called a block.
Loops are also called as iterative statements.
BREAK AND CONTINUE:
C allows the break and continue statements to stop a particular iteration of a
loop / block early, for instance if an abnormal condition occurs.
A break statement inside the body of a loop / block breaks out of the loop /
block. No more instructions in the body of the loop / block are executed, and the next
statement after the loop / block will be executed.
The continue statement just skips any instructions after it on that iteration of the
loop. The current iteration of the loop is terminated, and the loop statement executed
again as if the last instruction of the loop body has been reached.
The exit ( ) function:
It causes immediate termination of the program and execution return to the
operating system.
break terminates the execution of loop or switch in which it is written, whereas
exit( ) terminates the execution program itself.

PREPROCESSOR DIRECTIVES:
C processor is a program that processes our source program before it is
passed to the compiler. Preprocessor commands often known as directives.

14

Preprocessor directives begin with a # symbol.


The directives placed anywhere in a program but are most often placed at the
beginning of a program, before the first function definitioin.
C source code(xyz.c)---Preprocessor------Expanded source code(xyz.i)-----------Compiler-----Object code(xyz.obj) ------Linker-----Executable code(xyz.exe)
Ex:

#define pi 3.14 -----------MACRO


#define AND &&
#define OR ||
#define x(a>b AND a>c) -------- NESTED MACRO
#define XYZ printf(how are you);
#define SQUARE(n) n*n -------MACRO with argments

Other Directives: #ifdef, #endif, #else, #elif, #pragma,


A macro definition is never to be terminated by a semicolon.

ARRAYS:
An array is a collection of elements of same data type. The individual
elements of an array can be referenced by means of its index (subscript). Arrays index
starts from zero. That is, if we declare an array of size n, we can refer the elements
from 0 to (n-1)th element. Array types are
$ One dimensional $ Two dimensional $ Three dimensional $ Multi dimensional
Syntax:

data-type var-name [size];


int x[10];
char name[20];
float f[5];

We can initialize array elements at the time of declaration.


Int x[10]={100,200,-146,345};
char name[20]={R,A,V,I,N,D,E,R,\0};
float f[ ]={43.6, 33,21, -5.3};
The size of an array can be omitted in the declaration. If the size is omitted,
then the compiler will reserve the memory location corresponds to number of
individual elements that includes in the declaration.

15

If we give values less than the size of an array some compilers initializes rest of
elements by spaces or zeroes.
C will not allow to specify repetition of an initialization, or to initialize an element
in the middle of an array without supplying all the preceding values.
Two dimensional syntax: data-type var-name [rows] [cols];
Ex: int x[3][4]={ {10, 20, 30, 40},
{50, 60, 70, 80},
{11, 22, 33, 44}
};
Since, the array elements are stored in adjacent locations, the above declaration also
can be written as
Int x[3][4]= {10, 20, 30, 40, 50, 60, 70, 80, 11, 22, 33, 44};
While initializing an array it is necessary to mention the second (column)
dimension, where as the first dimension (row) is optional.
Multi-dimensional arrays can be declared in C just by adding more subscripts.
The general form of multi-dimensional array is
data-type var-name [size1] [size2] [size3].. [sizen] ;
There is no restriction on the number of dimensions in C but it is limited only by
the amount of memory available to the program.
FUNCTIONS:
A self-contained block of statements is called a function.
Advantages:
1) reusability
2) debugging is easy
3) decreases the program complexity etc
Syntax: return-type function-name (parameter list)
{
Parameter declaration;
Body of function;
}

Parameter list (also called argument list) is optional.

Variables declared in functions are called local variables and the scope is
limited to that function itself.

16

Function performs the same set of instructions on different sets of data or at


different portions of a program.

If the function does not return any value then write void before the function.

The return type in function declaration is optional. If no return type is specified


by default C returns the int data-type.

A function can be called from any function in C.

A function which is referring another function is called calling function.

A function which is referenced by another function is called called function.

The parameters mentioned in function call are called actual parameters.

The parameters in the function declaration are called formal parameters.

We can pass more than one parameter to a function but function returns a
single value.

Every program in C starts from the main() function.

On completion of the function it returns control back to the statement where it


left the calling program.

Function call can appear either independently or within an expression.

C allows declaring the type of parameters along with the parameters itself.

All C programs must contain atleast one function.

There may be any number of return statements in function definition, but only
one statement will active in a function call.

A function can return only one value.

The variable declarations within the function are local to the function and are
not available outside the function.

There should be one to one correspondence between the actual and formal
parameters in type, order and number.

A function can not be defined in another function. But we can declare any
number of functions.

Function Prototype:
Before defining a function other than main ( ), first we have to declare it. The
declaration of a function is known as function prototype.

A function prototype contains the function name and the data type of return
value, and the parameters and their types.

17

These prototypes appear at the starting of the program before main ( ).

In case, the complete function is defined before main ( ), then the declaration
prototype is not required.

We can pass values to function by 2 methods.

1) Call by value: Here we are calling a function by sending variable values. In this
we pass copy of variable values. In program even you change the formal
parameters; we can not find change in the actual parameters.
2) Call by reference: Here we are calling a function by sending variable addresses.
So the function receives reference to variable and works directly with the original
variable.
Recursion:
If a function called by it-self then it is known as recursion.

Every recursive function must have a terminating condition.

It eliminates the writing more statements to solve a problem.

Storage Classes:
We can declare variables in 3 places.
1) inside the function local variables
2) outside of all functions global variables
3) in the definition of function parameters block variables
The storage classes tell how, when and where storage will be allocated for the
variable. In C we have 4 types of storage classes.

S.C

Type

auto
(default-

Local

local)

register

static

Local

Local

Initial
value

Declaration

Garbage Within function


value

or block

Garbage Within function


value

or block

Within function
or block

18

Storage

Memory

CPU
Registers

Memory

Scope

Lifetime

Within

Until

function

function no

or block

longer active

Within

Until

function

function no

or block

longer active

Within

Between

function

different

or block

function

calls
Programs

extern
(default- Global

global)

Within
program

Memory

Within all

execution

programs

does not
come to end

The initial value for a global variable must be a constant, whereas a local
variable may contain variables.

A local variable loses its value, the moment the function or block containing it is
exited. Whereas global variables retain their values throughout their execution.

Using register variables we can increase the speed of a program.


Register variables does not contain addresses.
Static variables gets initialized to zero automatically, is initialized only once
during program startup.

If we write static before function then it become inaccessible outside the file.
STRINGS:
Group of alphanumeric characters enclosed within double quotes is
known as string. Ex: computer, 1234, 8, ad34cx+&z, *-/+ etc.

There is no sting built-in data type in C.


But we can declare string as an array of characters.
To recognize a character array, it should end with a null character (\0).
Syntax:
Ex:

char str-name[size];
char name[10];

Initialization:

char name[10]=raghu; or
char name[10]={r,a,g,h,u,\0}; or
char date [ ] =27-01-2007;

Reading Strings:
We can use scanf( ), gets( ), getchar( ) functions to read strings.

In scanf( ) function use %s format specifier, and do not write & symbol
before string variable name. This is because, C treats the array name itself
as the address of first location of an array.

19

One of the limitations of the scanf( ) function is that it is not capable of


holding multiword strings, it does not read characters whenever it find space
or new line.

To overcome this problem, we can use gets( ) function. It will read string until
encounters a new line. It reads entire string at a time.

getchar( ) function reads single character by character.


We can not assign one to another string directly. We can copy one string to
another string character by character only.

sprintf( ) writes the output to an array of characters.


Syn: sprintf(char-array, f.s, var-list);

sscanf( ) reads the dat from an character array.


We can perform arithmetic operations on characters also.
There are different types of built-in functions that will check the type of
character entered into a program.

Header file for those functions is ctype.h


MEANING

FUNCTION

return a non-zero if character or zero

isalphanum( )

Alphabetic or numeric

isalpha( )

Alphabetic

isdigit( )

Decimal digit

islower( )

Checks if character is lowercase

isupper( )

Checks if character is uppercase

isspace( )

White space

The following are commonly used data conversion functions in C library


to convert string of digits to numeric values and vice-versa.
Data-conversion functions:
atoi(s) --- converts string to int
atof(s) --- converts string to float
atol(s) --- converts string to long
itoa(s) --- converts int to string
String handling functions:
Header file is string.h

20

S.No

Function

Meaning

strlen(s1)

Returns length counts spaces also but not null character

strrev(s1)

Prints s1 in reverse order

strlwr(s1)

Prints s1 in lower case

strupr(s1)

Prints s1 in upper case

strcat(s1, s2)

Append s2 to s1

strncat(s1, s2, n) Append s2 first n characters to s1

strcpy(s1, s2)

Copies s2 to s1

strncpy(s1, s2)

Copies s2 first n characters to s1

strcmp(s1, s2)

Compares s1, s2 if s1==s2 returns 0, if s1>s2 =>1, if

s1<s2 => -1

10

strncmp(s1,s2,n) Compares first n characters of s1 and s2

11

strcmpi(s1,s2)

Compares s1 and s2 without case sensitivity

strchr(str,search

Searches given character in the string

12
13

char)
strtok(str,char)

Spilts the string with the character

POINTERS:
Pointers are useful to work with memory address, to allocate memory
dynamically and to effectively represent complex data structures.
A pointer is a variable which holds address of another variable.
Syn: datatype * var-name;
Ex: int *x; char *p; or int* x, char* p;
Note that *(indirection operator) is part of variable type, not part of the name itself.

Char* p1, p2;


Here p1 is pointer and p2 is just character.
A pointer can assign to another pointer. This will cause both the pointers point to
the same object.
A pointer can be incremented / decremented. The result is to cause the pointer to
point to the subsequent / previous element.
We can not perform multiplication, division operations on pointers.
An integer can be added to or subtracted from a pointer.

21

One pointer can be subtracted from another pointer but can not be added. The
expression returns the number of elements between them.
By using pointers the memory can be allocated or de-allocated dynamically. But it
is not possible with arrays.
The unary operator & is used to know the address of variable.
The unary operator * is used to know the value at the address location of a
variable.
& is called reference operator and * is called de-reference operator.
A global pointer variable gets initialized to a NULL pointer. NULL pointer address
is 0. We should not apply * on a NULL pointer because 0 th location usually used
by operating system.
Let ptr= 20 ptr = ptr+2; now the value of pte is 24 not 22
= 2*sizeof(int) = 2*2 = 4
Pointers to constant objects:
const int* pi;
int x[10];
pi=x;
*pi=200; or pi[4]=300; or not valid. But pi itself can be changed like pi++.
Constant pointers:
int * const pi=x;
*pi=100; is valid but pi++ is not valid.
const int * const pi=x; will disallow any modification to pi or the integer
which pi is pointing to.

COMAND LINE ARGUMENTS:


During the execution of a program, arguments can be passed to the main( )
function through command line arguments.
The main( ) prototype is: int main( int argc, char *argv[ ])
argc stands for the argument count. Its value is the number of arguments in the
command line that was used to execute the program.
Argv stands for argument vector. The program name is the first word on the
command line, which is argv [0]. The command line arguments are argv[1]
through argv [argc-1].

22

STRUCTURES and UNIONS:


A structure is a collection of variables of different data types; that are
logically grouped together and referenced under one name.
C allows us to create new data types using structures and unions.
A union is also a collection of variables of different data types. unlike structures,
the variables share the same memory area.
Syntax: struct structure-tag
{
Var-1;
Var-2;
-------;
Var-n;
}; // } str-var1, var2, ;
Struct is a keyword. If there is only one structure variable then the structure name
is an optional.
The members of a structure are often called structure elements.
We can access the structure elements by using period(.) operator if a structure
variable is an ordinary variable or use arrow(->) operator if a structure variable is a
pointer.
Initialization: struct stu s={01, raghu, IT};
Uses of Structures:
In the database management
Clearing the contents of the screen
Placing the cursor at an appropriate position on screen
Drawing any graphics shape on the screen
Receiving a key from keyboard
Checking the memory size of the computer
Formatting a floppy
Hiding a file from the directory
Sending the output to printer
Interacting with the mouse etc
Structure with array is struct str-tag str-var[size];

23

We can structure elements to function in 3 ways.


1) structure elements separately
2) entire structure
3) pointer to structure
structure variables can also be returned. This means that a function can be
declared of structure type.
Self-referential structures: A structure that contains an elements, which point to
the structure of same type, is known as self-referential structures.
Ex: struct list
{
Int value;
Struct list *next; };
Self-referential structures are useful to define some data structures such as
linked lists and trees.
Using unions we can save memory.
The total size of structure is equal to the total size of each structure element.
Whereas union is equal to the largest union element size.
If we do not write structure or union variable then the compiler does not create
memory.
BITFIELDS:
Using bit fields we can save memory in structure or union.
Struct str-tag { var:length,..};

FILES:
A file is a collection is a data stored permanently on secondary storage
devices such as disks, optical disks and tapes etc.
C works with files using a new data type called a file pointer.
C treats data file as a stream of characters. A stream is a general name given
to a flow of data.
C provides a data structure FILE declared in header file stdio.h to access the
streams of characters from the disk files. It acts as a link between OS and our
program.
Syntax: FILE *pointer-name;

24

File Operations:
1) open 2) close

3) rename

4) update

5) copy

6) append etc

Open:
fopen (file name, mode);
The different modes are

Mode
r

Description
Read. If the file does not exist it returns NULL value.
write. If file already exist, its contents are overwritten. Otherwise a new

file is created. It returns NULL if unable to create file and if there is no


space in disk etc.
append. If file already exist, the new data in adds at the end of file.

Otherwise a new fill is created. It returns NULL if unable to create file


and if there is no space in disk etc.

r+

read & write. The file must exist

w+

read & write. Overwrites file data

a+

read & append. If file not exist the file is created

CLOSE:

fclose (file-pointer);

However, C closes all the files that are opened when the execution of the
program is completed.
Built-in File functions:
fputc (char-variable, file-pointer);
fgetc (file-pointer);
fputs (string-variable, file-pointer);
fgets (string-variable, length, file-pointer);
fscanf(file-pointer, format string, argument list);
fprintf(file-pointer, format string, argument list);
x = ftellp(file-pointer); - returns long integer which corresponds to the
current position in the file.
rewind(file-pointer); - moves file pointer to the beginning of a file. Rewind
is done implicitly whenever a file is opened.
fseek(file-pointer, off-set, position);
Here the position is 3 types.
1) 0 indicates beginning of the file

SEEK_SET

25

2) 1 - indicates current position

SEEK_CUR

3) 2 - indicates end of file

SEEK_END

The fseek( ) is used to move the file pointer position to desired location.
The offset may be positive or negative. A positive value moves the pointer
toward the end of the file, while the negative offset moves the pointer towards
the beginning of the file.
The negative offset is used only when the position is 1.
fseek (fp, 0L, 0); - goto beginning of the file
fseek (fp, -10L, 1); - move backwards 10 bytes from the current position
EOF = -1. NULL = 0
Text Files and Binary Files:
A text file contains only textual information like alphabets, digits and special
symbols. A binary file is merely a collection of bytes. We can open a file in binary
mode use rb, wb, ab modes in place of r, w, a etc. Defualt mode is text mode so we
no need to write rt, at, wt etc.
In binary file there is no new line character, EOF.
In text mode the value 3865 occupies 4 bytes where as in binary mode only 2
bytes.

DATA STRUCTURES
Data structure is a study of different methods of organizing the data and
possible operations on these structures.
Data structures are classified into 2 types
1) Linear organize the data in a linear sequence like elements in an array.
Ex: array, stack, queue
2) Non-linear - organize the data in a non-linear fashion.
Ex: trees, graphs
The complexity of algorithms in terms of time and space is specified by O
(spelled by Big-Oh) notation.
A function f is a complexity of order at most g(n), written with big-oh notation as
f=O(g), if there exist a positive constant c and a positive integer n 0 such that
| f(n) | c.|g(n)|

for all nn0

26

The usage of O notation is very simple. For example, if the time or memory required to
execute an algorithm to N (N is total number of elements), we write the algorithm
complexity is O(N). The constants factors do not affect the complexity. For example
O(2N) = O(N).

27

Vous aimerez peut-être aussi