Sie sind auf Seite 1von 29

C was developed in the early 1970s by Dennis Ritchie at Bell Laboratories.

C was originally
designed for writing system software bt today a variety of software programs are written in C. C
can be sed on many different types of compters bt is mostly sed with the !"#$ operating
system.
#t is a good idea to learn C becase it has been arond for a long time which means there is a lot
of information available on it. %ite a few other programming langages sch as C&& and 'ava
are also based on C which means yo will be able to learn them more easily in the ftre.
What you will need
(his ttorial is written for both )indows and !"#$*Lin+ sers. ,ll the code in the e+amples
has been tested and wor-s the same on both operating systems.
#f yo are sing )indows then yo need to download borland C&& compiler from
http.**www.borland.com*cbilder*cppcomp. /nce yo have downloaded and installed it yo need
to add 0C:\Borland\BCC55\Bin0 to yor path. (o add it to yor path in )indows 91*92*34 yo
need to add the line 0PATH=C:\Borland\BCC55\Bin0 to c:\autoexec.bat sing notepad. #f yo
are sing )indows "(*5000*$6 then yo need to open the control panel and then doble clic-
on 0system0. Clic- on the 0,dvanced0 tab and then clic- 04nvironment 7ariables0. 8elect the
item called 06ath0 and then clic- 04dit0. ,dd 09C:\Borland\BCC55\Bin0 to 07ariable vale0 in
the dialog bo+ that appears and then clic- /- and close everything.
,ll )indows sers will now have to create a te+t file called 0bcc:5.cfg0 in
0C.;Borland;BCC11;Bin0 and save the following lines of te+t in it.
-IC:\Borland\BCC55\include
-!C:\Borland\BCC55\lib
#f yo are sing !"#$*Lin+ then yo will most probably have a C compiler installed called
<CC. (o chec- if yo have it installed type 0cc0 or 0"cc0at the command prompt. #f for some
reason yo don=t have it then yo can download it from http.**gcc.gn.org.

#our $ir%t &ro"ra'
(he first thing we mst do is open a te+t editor. )indows sers can se "otepad and
!"#$*Lin+ sers can se emacs or vi. "ow type the following lines of code and then # will
e+plain it. 3a-e sre that yo type it e+actly as # have or else yo will have problems. ,lso don=t
be scared if yo thin- it is too complicated becase it is all very easy once yo nderstand it.
Code.
1
5
:
>
1
?
7
#include<stdio.h>
int main()
{
printf("Hello World\n");
return 0;
}
(include)%tdio.h*
(his incldes a file called stdio.h which lets s se certain commands. stdio is short for 8tandard
#npt*/tpt which means it has commands for inpt li-e reading from the -eyboard and otpt
li-e printing things on the screen.
int 'ain+,
int is what is called the retrn vale which will be e+plained in a while. main is the name of the
point where the program starts and the brac-ets are there for a reason that yo will learn in the
ftre bt they have to be there.
-.
(he 5 crly brac-ets are sed to grop all the commands together so it is -nown that the
commands belong to main. (hese crly brac-ets are sed very often in C to grop things
together.
&rint$+Hello World\n,/
(his is the printf command and it prints te+t on the screen. (he data that is to be printed is pt
inside brac-ets. @o will also notice that the words are inside inverted commas becase they are
what is called a string. 4ach letter is called a character and a series of characters that is groped
together is called a string. 8trings mst always be pt between inverted commas. (he ;n is called
an escape seAence and represents a newline character and is sed becase when yo press
4"(4R it doesn=t insert a new line character bt instead ta-es yo onto the ne+t line in the te+t
editor. @o have to pt a semiBcolon after every command to show that it is the end of the
command.
(able of commonly sed escape seAences.
\a ,dible signal
\b Bac-space
\t (ab
\n "ewline
\0 7ertical tab
\$ "ew page;Clear screen
\r Carriage retrn
return 1/
(he int in int 'ain+, is short for integer which is another word for nmber. )e need to se the
retrn command to retrn the vale 0 to the operating system to tell it that there were no errors
while the program was rnning. "otice that it is a command so it also has to have a semiBcolon
after it.
8ave the te+t file as hello.c and if yo are sing "otepad ma-e sre yo select ,ll Ciles from the
save dialog or else yo won=t be able to compile yor program.
@o now need to open a command prompt. #f yo are sing )indows then clic- 8tartBDRn and
type 0command0 and Clic- /-. #f yo are sing !"#$*Lin+ and are not sing a graphical ser
interface then yo will have to e+it the te+t editor.
!sing the command promptE change to the directory that yo saved yor file in. )indows sers
mst then type.
C:\*bcc23 hello.c
!"#$*Lin+ sers mst type.
4cc hello.c -ohello
(he Bo is for the otpt file name. #f yo leave ot the Bo then the file name a.ot is sed.
(his will compile yor C program. #f yo made any mista-es then it will tell yo which line yo
made it on and yo will have to type ot the code again and this time ma-e sre yo do it e+actly
as # did it. #f yo did everything right then yo will not see any error messages and yor program
will have been compiled into an e+e. @o can now rn this program by typing 0hello.e+e0 for
)indows and 0.*hello0 for !"#$*Lin+.
@o shold now see the words 0Fello )orld0 printed on the screen. CongratlationsG @o have
Hst made yor first program in C.
Indentation
@o will see that the printf and retrn commands have been indented or moved away from the
left side. (his is sed to ma-e the code more readable. #t seems li-e a stpid thing to do becase
it Hst wastes time bt when yo start writing longerE more comple+ programsE yo will
nderstand why indentation is needed.
5%in" co''ent%
Comments are a way of e+plaining what a program does. (hey are pt after 66 or between 67 76.
Comments are ignored by the compiler and are sed by yo and other people to nderstand yor
code. @o shold always pt a comment at the top of a program that tells yo what the program
does becase one day if yo come bac- and loo- at a program yo might not be able to
nderstand what it does bt the comment will tell yo. @o can also se comments in between
yor code to e+plain a piece of code that is very comple+. Fere is an e+ample of how to
comment the Fello )orld program.
Code.
1
5
:
>
1
?
7
2
9
10
11
15
! "uthor# $%schools.in
&ate# '00()0()0*
&escription#
Writes the $ords "Hello World" on the screen !
#include<stdio.h>
int main()
{
printf("Hello World\n"); prints "Hello World"
return 0;
}
!earn C - 8ata ty&e%
Data types in any of the langage means that what are the varios type of data the variables can
have in that particlar langage. )henever a variable is declared it becomes necessary to define
data type that what will be the type of data that variable can hold. (he varios general types of
data are.
9. :u'ber ty&e data
3. Character ty&e data
2. ;trin" ty&e data
<. Boolean ty&e data
"mber type data again inclde to main classesE they can be either integers that is whole nmber
or they can be the real nmber that is decimal part.
C langage also spports the wide range of data type li-e
Char
sed to represent the character type data
I1 byte memory is allocatedE Range is B152 to & 157J.
Int
to represent the integer type data.
I5 byte memory is allocated Range is K :57?2 to :57?7J.
=loat
!sed to represent the real type data.
I> byte memory is allocated Range is :.> + 10LB:2 to :.> +
!on"
!sed to represent the integer type data having long range.
I2 byte memory is allocated Range is BJ.
8ouble
!sed to represent the float type data in the long range.
I1? byte memory is allocated Range is K 1.7c :02 to 1.7c :02J.
!on"
8ouble
!sed to represent the float type data in even more long range then
the doble. I:5 byte memory is allocated E 1.7c >9:5 & 1.7c >9:5
!earn C - >ariable% and con%tant%
What are 0ariable%?
7ariables in C are 'e'ory location% that are given names and can be assigned vales. )e se
variables to store data in memory for later se. (here are 5 basic -inds of variables in C which
are nmeric and character.
:u'eric 0ariable%
"meric variables can either be integer vales or they can be Real vales. #nteger vales are
whole nmbers withot a fraction part or decimal point in them. Real nmbers can have a
decimal point in them.
Character 0ariable%
Character variables are letters of the alphabet as well as all characters on the ,8C## chart and
even the nmbers 0 B 9. Characters mst always be pt between single Aotes. , nmber pt
between single Aotes is not the same thing as a nmber withot them.
What are con%tant%?
(he difference between variables and constants is that variables can change their vale at any
time bt constants can never change their vale. Constants can be sefl for items sch as 6i or
the charge on an electron. !sing constants can stop yo from changing the vale of an item by
mista-e.
8eclarin" 0ariable%
(o declare a variable we first pt the type of variable and then give the variable a name. (he
following is a table of the names of the types of variables as well as their ranges.
"ame (ype Range
int "meric B #nteger B:5 7?2 to :5 7?7
%hort "meric B #nteger B:5 7?2 to :5 7?7
lon" "meric B #nteger B5 1>7 >2: ?>2 to 5 1>7 >2: ?>7
$loat "meric B Real 1.5 $ 10
B:2
to :.> $ 10
:2
double "meric B Real 5.5 $ 10
B:02
to 1.2 $ 10
:02
char Character ,ll ,8C## characters
@o can name a variable anything yo li-e as long as it incldes only lettersE nmbers or
nderscores and does not start with a nmber. #t is a good idea to -eep yor variable names less
than :5 characters long to save time on typing them ot and for compiler compatibility reasons.
7ariables mst always be declared at the top before any other commands are sed. "ow let=s
declare an integer variable called a and a character variable called b.
Code.
1
5
:
>
1
?
int main()
{
int a;
char +;
return 0;
}
@o can declare more than one variable at the same time in the following way.
Code.
1
5
:
>
1
int main()
{
int a,+,c;
return 0;
}
(o declare a constant all yo have to do it pt the word const in front of a normal variable
declaration and ma-e assign a vale to it.
Code.
1
5
:
>
1
int main()
{
const float pi - %../;
return 0;
}
;i"ned and un%i"ned 0ariable%
(he difference between signed and nsigned variables is that signed variables can be either
negative or positive bt nsigned variables can only be positive. By sing an nsigned variable
yo can increase the ma+imm positive range. )hen yo declare a variable in the normal way it
is atomatically a signed variable. (o declare an nsigned variable yo Hst pt the word
nsigned before yor variable declaration or signed for a signed variable althogh there is no
reason to declare a variable as signed since they already are.
Code.
1
5
:
>
1
?
int main()
{
unsi0ned int a;
si0ned int +;
return 0;
}
5%in" 0ariable% in calculation%
(o assign a vale to a variable yo se the eAals sign.
Code.
1
5
:
>
1
?
7
2
int main()
{
int a;
char +;
a - %;
+ - "H";
return 0;
}
(here are a few different operators that can be sed when performing calclations which are
listed in the following table.
/perator /peration
@ ,ddition
B 8btraction
M 3ltiplication
* Division
N 3odlsIRemainder of integer divisionJ
(o perform a calclation yo need to have a variable to pt the answer into. @o can also se
both variables and normal nmbers in calclations.
Code.
1
5
:
>
1
?
7
2
int main()
{
int a,+;
a - *;
+ - a 1 %;
a - a ) %;
return 0;
}
Aeadin" and &rintin" 0ariable%
@o can read a variable from the -eyboard with the scanf command and print a variable with the
printf command.
Code.
1
5
:
>
1
?
7
2
9
10
#include<stdio.h>
int main()
{
int a;
scanf("2d",3a);
a - a ! ';
printf("4he ans$er is 2d",a);
return 0;
}
=or'at %&eci$ier%
when ever a variable has to be inptted then some registers the vales from the inpt nit and
transfers it to their respective memory locations. Fence it is reAired to specify the format of the
incoming data so that there is ease to send the corresponding no. of registers becase if the
format is not -nown to s then it becomes very difficlt for the processor of decide the nmber
of registers to send and in this case the ma+imm possible registers are send and in general case
it cases the memory loss. Fence this format specifiers are sed to save the memory. 8ome of
the common format specifiers sed in C are
Cormat specifier prpose
Bd integer data types
B$ float
Bu nsigned integers
B% string
Bc char
Bld long integer
!earn C - 8eci%ion%
The i$ %tate'ent
8o far we have only learnt how to ma-e programs that do one thing after the other withot being
able to ma-e decisions. (he if statement can be sed to test conditions so that we can alter the
flow of a program. (he following e+ample has the basic strctre of an if statement.
Code.
1
5
:
>
1
?
7
2
9
10
11
#include<stdio.h>
int main()
{
int mar5;
char pass;
scanf("2d",3mar5);
if (mar5 > /0)
pass - "6";
return 0;
}
#n the above e+ample the ser enters the mar- they got and then the if statement is sed to test if
the mar- is greater than >0. 3a-e sre yo remember to always pt the conditions of the if
statement in brac-ets. #f the mar- is greater than >0 then it is a pass.
"ow we mst also test if the ser has failed. )e cold do it by adding another if statement bt
there is a better way which is to se the else statement that goes with the if statement.
Code.
1
5
:
>
1
?
7
2
9
10
11
15
1:
#include<stdio.h>
int main()
{
int mar5;
char pass;
scanf("2d",3mar5);
if (mar5 > /0)
pass - "6";
else
pass - "n";
return 0;
}
(he if statement first tests if a condition is tre and then e+ectes an instrction and the else is
for when the reslt of the condition is false.
#f yo want to e+ecte more than 1 instrction in if statements then yo have to pt them
between crly brac-ets. (he crly brac-ets are sed to grop commands together.
Code.
1
5
:
>
1
?
7
2
9
10
11
15
1:
1>
11
1?
17
12
19
#include<stdio.h>
int main()
{
int mar5;
char pass;
scanf("2d",3mar5);
if (mar5 > /0)
{
pass - "6";
printf("7ou passed");
}
else
{
pass - "n";
printf("7ou failed");
}
return 0;
}
#t is possible to test 5 or more conditions at once sing the ,"D IOOJ operator. @o can se the
/R IPPJ operator to test if 1 of 5 conditions is tre. (he "/( IGJ operator ma-es a tre reslt of a
test false and vice versa.
Code.
1
5
:
>
1
?
7
2
9
10
11
15
1:
1>
11
#include<stdio.h>
int main()
{
int a,+;
scanf("2d",3a);
scanf("2d",3+);
if (a > 0 33 + > 0)
printf("8oth num+ers are positi9e\n");
if (a -- 0 :: + -- 0)
printf(""t least one of the num+ers - 0\n");
if (;(a > 0) 33 ;(+ > 0))
printf("8oth num+ers are ne0ati9e\n");
return 0;
}
Boolean o&erator%
#n the above e+amples we sed D and Q which are called Boolean operators. (hey are called
Boolean operators becase they give yo either tre or false when yo se them to test a
condition. (he following is table of all the Boolean operators in c.
== 4Aal
C= "ot eAal
* <reater than
*= <reater than or eAal
) Less than
)= Less than or eAal
DD ,nd
EE /r
C "ot
The %witch %tate'ent
(he switch statement is Hst li-e an if statement bt it has many conditions and the commands for
those conditions in only 1 statement. #t is rns faster than an if statement. #n a switch statement
yo first choose the variable to be tested and then yo give each of the conditions and the
commands for the conditions. @o can also pt in a defalt if none of the conditions are eAal to
the vale of the variable. #f yo se more than one command then yo need to remember to
grop them between crly brac-ets.
Code.
1
5
:
>
1
?
7
2
9
10
11
15
1:
1>
11
1?
17
12
19
50
51
55
5:
5>
51
5?
#include<stdio.h>
int main()
{
char fruit;
printf("Which one is 6our fa9ourite fruit#\n");
printf("a) "pples\n");
printf("+) 8ananas\n");
printf("c) <herries\n");
scanf("2c",3fruit);
s$itch (fruit)
{
case "a"#
printf("7ou li5e apples\n");
+rea5;
case "+"#
printf("7ou li5e +ananas\n");
+rea5;
case "c"#
printf("7ou li5e cherries\n");
+rea5;
default#
printf("7ou entered an in9alid choice\n");
}
return 0;
}
!earn C - !oo&%
the 0ariou% control %tructure% in C
Control strctres are the statements which controls the overall any program. Control strctres
are basically of three types K
;eFuence %tate'ent%
Iterati0e %tate'ent%
;election %tate'ent%
;eFuence ;tate'ent% : ,ll the 8tate in a program e+cept the iterative O statements. (hey are
generally the individal statements which performs the tas- of inptE otptE assignment
declaration etc.
Iterati0e ;tate'ent are those repeated e+ection of a particlar set of instrctions desired
nmber of times. (hese statements are generally called loops for their e+ection natre. Loops
are basically of two types K
o Count !oot
o G0ent !oo&
Count !oo& :- (hose loops whose no. of times of e+ection is -nown prior to the
e+ection of loop are termed as cont loops i.e they care contable in natre.
G0ent !oo& :- (hose loop whose e+ection any certain event are called event
before the e+ection.
, loop basically consists of a loop variable which has for the completion of any
iterative statementE i.e a loop consists of three main statements.B
+9, InitialiHation +3, Condition +2, Incre'entation
#nitialiRation is sed to start any loop i.e. it gives some initial vale to the loop variable.
)hich defines that from which vale the loop has to get start. Condition is provided to give the
final vale to the loop variable so that how many times the loop has to get e+ected. Cor reaching
the loop variable from initial vale to the final vale there shold be some sort of
increamentation and that provided by the third component statement of loop and that is
incrementation.
#f in any loop the incramentation or the final vale is not provided then the loop becomes
infinite. #f the initialiRation is not done then the garbage vale of the loop variable becomes its
initial vale.
#n C langage the iterative statements IloopsJ can be implemented in the three loops and
they are
The $or loo&
8ynta+ of Cor Loop K
for IinitialiRation9 condition9 incrementationJ
S BBBBBBBBBBBBBBBBB body of loop BBBBBBBBBBBBB
T
Cor Loop will perform its e+ection ntil the condition remains satisfied. #f the body of the
loop consists of more than one statement then these statements are made compond by placing
the open and closed crly brac-ets arond the body of the loop. Cor loop is a cont loop. (he
initialiRation condition and increamentation may be done in the same statement. Cor loop will not
e+ecte at least once also if the condition is false at the first time itself.
)ith loops yo also have to pt commands between crly brac-ets if there is more than one of
them. Fere is the soltion to the problem that we had with the 5> printf commands.
Code.
1
5
:
>
1
?
7
2
9
#include
int main()
{
int i;
for (i - .;i <- '/;i11)
printf("H\n");
return 0;
}
, for loop is made p of : parts inside its brac-ets which are separated by semiBcolons. (he first
part initialiRes the loop variable. (he loop variable controls and conts the nmber of times a
loop rns. #n the e+ample the loop variable is called i and is initialiRed to 1. (he second part of
the for loop is the condition a loop mst meet to -eep rnning. #n the e+ample the loop will rn
while i is less than or eAal to 5> or in other words it will rn 5> times. (he third part is the loop
variable incremental. #n the e+ample i&& has been sed which is the same as saying i U i & 1.
(his is called incrementing. 4ach time the loop rns i has 1 added to it. #t is also possible to se
iBB to sbtract 1 from a variable in which case it=s called decrementing.
The while loo&
8ynta+ K
#nitialiRation9
)hile IconditionJ
S
Body of loop9
#ncrementation9
T
#n this loopE initialisationE condition and incrementation is done in the three different statements.
(his loops is cont as well as event loop. #n case of while loops the body of the loop will consist
of more than one statements becase each time one statement will be of incrementation. Fence
the open and closed crly brac-ets are reAired.
Code.
1
5
:
>
1
?
7
2
9
10
11
15
1:
1>
#include<stdio.h>
int main()
{
int i,times;
scanf("2d",3times);
i - 0;
$hile (i <- times)
{
i11;
printf("2d\n",i);
}
return 0;
}
The do while loo&
(he third loop statement available in C is doBwhile statement synta+ .B
#nitialiRation9
Do
S
Body of loop9
#ncreamentation9
T
)hile IconditionJ9
#n this loop the condition is chec-ed at the endE and for this reason this loop will e+ecte at least
once whether the condition may be satisfying and nsatisfying.
Code.
1
5
:
>
1
?
7
2
9
10
11
15
1:
1>
11
#include<stdio.h>
int main()
{
int i,times;
scanf("2d",3times);
i - 0;
do
{
i11;
printf("2d\n",i);
}
$hile (i <- times);
return 0;
}
BreaI and continue
@o can e+it ot of a loop at any time sing the brea- statement. (his is sefl when yo want a
loop to stop rnning becase a condition has been met other than the loop end condition.
Code.
1
5
:
>
1
?
7
2
9
10
11
15
1:
#include<stdio.h>
int main()
{
int i;
$hile (i < .0)
{
i11;
if (i -- *)
+rea5;
}
return 0;
}
@o can se contine to s-ip the rest of the crrent loop and start from the top again while
incrementing the loop variable again. (he following e+ample will never print 0Fello0 becase of
the contine.
Code.
1
5
:
>
1
?
7
2
9
10
11
15
1:
#include<stdio.h>
int main()
{
int i;
$hile (i < .0)
{
i11;
continue;
printf("Hello\n");
}
return 0;
}
What are &ointer%
(he simple variables are sed to store the literal vales. )henever a variable is declared in a
program it is having same memory location in the storage device. (he memory location is called
address of that variable. Fence there are some vales which do not hold the literal vales bt
stores the address Imemory addressJ of any other variable. 8ch variables are called pointers
I(he pointers in VCW langage increase the efficiency of program to a large e+tent. 4fficiency of
program to a large e+tent. ,lthogh they are difficlt to se bt it is a very powerfl tool. )hile
managing the memory. 6ointers are sed for many reasons li-e .B
6ointers redce the length and comple+ city of program.
(hey increase the processing speed.
(hey save the memory to a very large e+tent.
, pointer enables to access any variable whether it may be otside the fnction i.e. a
direct control over a variable can be made sing pointers.
(o declare a pointer yo mst pt a 7 in front of its name. Fere is an e+ample of how to declare a
pointer to an integer and an ntyped pointer.
Code.
1
5
:
>
1
?
int main()
{
int !p;
9oid !up;
return 0;
}
@o can pt the address of an integer into a pointer to an integer by sing the O operator to get
the integer=s address.
Code.
1
5
:
>
1
?
7
2
int main()
{
int i;
int !p;
i - *;
p - 3i;
return 0;
}
@o can access the vale of the integer that is being pointed to by dereferencing the pointer. (he
M is sed to dereference a pointer. Changing the vale pointed to by the integer will change the
vale of the integer.
Code.
1
5
:
>
1
?
7
2
9
10
int main()
{
int i,=;
int !p;
i - *;
p - 3i;
= - !p; = - i
!p - >; i - >
return 0;
}
How the &ointer% are initialiHed and de$ine how 0ariable can be acce%%ed throu"h &ointer
+Arith'etic,?
(he pointer variables are declare by sing the pointer notation IastricEMJ. (hey are also associated
with a data type which will represent the type of data to which that particlar pointer is pointing.
Fere pointer variable is different from simple variables in the sense that they cannot store some
literal vale bt will store the address of any particlar memory location. Fence it the memory
location has to be stored in the pointer variable then sch process is called pointer initialiRation.
(he pointer initialiRation when done then it shold be -ept in the mind that the pointer only that
memory location on which the same data type item is stored to which the pointer variable can
point.
4+ample .B
#nt MaEbE Md9
Cloat cE Me9
,UOb9
DUOc9
CUOc9
(he first statement will assign the address of VbW variable memory location to the pointer VaW
pointer VaW is pointing to an integer type memory location and VbW is an integer variable.
#n second statement the pointer variable is invalidE since VdW is an integer pointer and VcW is a float
type variable. Fence integer type pointer cannot store the float type data address.
(he third statement is valid since a float type pointer is pointing to a float type variable.
, 6ointer type variable is generally sed to access the vale of the variable to which pointer is
pointing. (his can be done by sing the indirection operation IMB content operatorJ. )hen the M is
placed in front of a pointerE it will be reslt in the content of that variable to which it is pointing.
Bt since the pointer variable is not having its own content hence it will access the content of
that variable to which it is pointing. Fence a vale of a variable can be accessed withot calling
that variableE throgh its pointer.
How the &ointer% can be u%ed with an array and how the &ointer% &ointin" to array% are
initialiHed?
array is a collection of mltiple data item which are represented by sing a single identifier.
8ince a single identifier representing all the data items will have generally a continos
allocation in arrays there is one base address to which all the contigos memory location are
attached. (hese memory location are having then difference in addresses and their addresses are
continos in manner.
, pointer variable is incremented by sing an increment operator then its address vale is not
increased by 1 bt it will be increased by a complete address this type of incrementation is called
pointer incrementation and the length the which pointer is incrementing is called scalar factor.
8ince the array is having a base address and all the memory location is continos in manner and
they store the data item of some type and the scalar factor can be sed in the pointers. Fence if a
pointer variable is made pointing to the base address of the any array then all sccessive element
of that array can be access by incrementing the pointer variable till the end of the array.
4+ample .
#nt a X10YE Mp9
6UOaX0Y9 X0Y
6UO aX10Y X10Y
(his will assign the base address of array VaW in the pointer variable p. "ow if the vale of the
second inde+ has to be accessed then the pointer p is incremented and now it is pointing to the
ne+t inde+ to the base address. (his can be done by sing increment operator li-e p&&.

!earn C - Array%
,rray by definition is a variable that hold mltiple elements which has the same data type.
#n case of a simple variable there is a very big problem that a single vale can be represented at a
time by a single identifier. Fence if we want to represent mltiple vales throgh a single
identifier than it is not possible throgh sing single identifier. Cor this prpose c has provided
yet another tool and it is called an array.
,n array is a collection of mltiple data items which are represented by the same identifier. (he
very main fondation is that all the vales shold be of same data types. #n the technical terms
the array is also called a script. (he varios locations where the vales can be stored are called
inde+es and in the technical terms they are referred as sbscripts. (he varios vales stored on
the inde+es are called the elements or the contents.
(he arrays are generally in the form of continos memory locations i.e. each memory location
is having the address of its ne+t memory location which is the part of that array. Fence arrays are
generally shown either in the form of rows or in the form of colmns strctre arrays are
basically classified into two main categories and these are .
9. 9-di'en%ional array
3. 3-di'en%ional array
9-di'en%ional array
,n array which is having either a single row or single colmn is termed as a oneBdimensional
array. /ne dimensional array have the sbscripts in a linear manner.
3-di'en%ional array
/neBdimensional array can store a list of linear variables bt for storing the vales which are in a
tablar formE the mltidimensional array are sed. (he mltidimensional arrays can be thogh of
having mltiple rows and colmns. #n factE when the wach inde+ of one dimensional array is
itself in the form of an array the pcoming strctre is called a mltidimensional array.
3ltidimensional arrays give the illsion of a matri+E since it is in the form of rows and colmn.
(he arrays in the C can be implemented by writing the data types of the elements along with the
array name and its inde+ nmbers Ino. of locationsJ.
8ynta+ .B
Data type array nameXsiReY9
(he array of characters is called string. (he array elements can be called ot by writing the array
name and its inde+ no. in the brac-ets.
5%in" array% with loo&%
(he most sefl thing to do with an array is se it in a loop. (his is becase the element nmbers
follow a seAence Hst li-e a loop does.
)hen an array is declared the vales are not set to 0 atomatically. @o will sometimes want to
set the vales of all elements to 0. (his is called initialiRing the array. Fere is an e+ample of how
to initialiRe an array of 10 elements sing a for loop.
int aX10Y9
for Ii U 09i Q 109i&&J
aXiY U 09
Julti-di'en%ional array%
,n array with more than one inde+ vale is called a mltidimensional array.
(he arrays we have been sing so far are called 1Bdimensional arrays becase they only have
what can be thoght of a 1 colmn of elements. 5Bdimensional arrays have rows and colmns.
Fere is a pictre which e+plains it better.
9-di'en%ional array
1 1
9 5
3 :
3-di'en%ional array
1 9 3
1 1 5 :
9 > 1 ?
3 7 2 9
@o do get :Bdimensional arrays and more bt they are not sed as often. Fere is an e+ample of
how yo declare a 5Bdimensional array and how to se it. (his e+ample ses 5 loops becase it
has to go throgh both rows and colmns.
int aX:YX:YEiEH9
for Ii U 09i Q :9i&&J
for IH U 09H Q :9H&&J
aXiYXHY U 09


):
5009B11B5: 11.11.>2 ?17day

<atam
5009B11B5: 15.11.19 ?17day

Cind greatest nmber in C
5010B15B0? 55.15.15 579day
! ?ro0ram to count the no of positi9e and ne0ati9e num+ers!
#include< stdio.h >
9oid main( )
{
int a@*0A,n,countBne0-0,countBpos-0,C;
printf(DEFGnter the siHe of the arra6\nDEI);
scanf(DEF2dDEI,3n);
printf(DEFGnter the elements of the arra6\nDEI);
for C-0;C < n;C11)
scanf(DEF2dDEI,3a@CA);
for(C-0;C < n;C11)
{
if(a@CA < 0)
countBne011;
else
countBpos11;
}
printf(DEF4here are 2d ne0ati9e num+ers in the arra6\nDEI,countBne0);
printf(DEF4here are 2d positi9e num+ers in the arra6\nDEI,countBpos);
}
J. What are arra6 and $ha6 the6 are usedK
"ns) Cn case of a simple 9aria+le there is a 9er6 +i0 pro+lem
that a sin0le 9alue can +e represented at a time +6 a sin0le identitifire. Hen
ce if $e $ant to represent multipal 9alues
throu0h a sin0le identifire then it is not possi+le throu0h usin0 sin0le ident
ifire for this purpose "<" has pro9ided 6et
another tool and it is called an arra6.
!earn C - ;trin"%
, string is an array of characters. 8trings mst have a 0 or nll character after the last character
to show where the string ends. (he nll character is not inclded in the string.
(here are 5 ways of sing strings. (he first is with a character array and the second is with a
string pointer.
, character array is declared in the same way as a normal array.
char caX10Y9
@o mst set the vale of each individal element of the array to the character yo want and yo
mst ma-e the last character a 0. Remember to se Ns when printing the string.
char caX10Y9
caX0Y U =F=9
caX1Y U =e=9
caX5Y U =l=9
caX:Y U =l=9
caX>Y U =o=9
caX1Y U 09
printfI0Ns0EcaJ9
#include<stdio.h>
#include<conio.h>
9oid main(){
int num@*A,i,maL;
clrscr();
printf("?lease enter an6 fi9e num+er\n");
for(i-0;i<*;i11){
scanf("2d",3num@iA);
}
maL-num@0A;
for(i-.;i<*;i11){
if(num@iA>maL){
maL-num@iA;
}
}
printf("0reatest no is) 2d", maL);
0etch();
}
8tring pointers are declared as a pointer to a char.
char Msp9
)hen yo assign a vale to the string pointer it will atomatically pt the 0 in for yo nli-e
character arrays.
char Msp9
sp U 0Fello09
printfI0Ns0EspJ9
@o can read a string into only a character array sing scanf and not a string pointer. #f yo want
to read into a string pointer then yo mst ma-e it point to a character array.
char caX10YEMsp9
scanfI0Ns0EcaJ9
sp U ca9
scanfI0Ns0EspJ9
;trin" handlin" $unction%
(he strings.h header file has some sefl fnctions for wor-ing with strings. Fere are some of
the fnctions yo will se most often.
%trc&y+de%tinationK%ource,
@o can=t Hst se string1 U string5 in C. @o have to se the strcpy fnction to copy one string
to another. strcpy copies the sorce string to the destination string.
s1 U 0abc09
s5 U 0+yR09
strcpyIs1Es5J9 // s1 = "xyz"
%trcat+de%tinationK%ource,
'oins the destination and sorce strings and pts the Hoined string into the destination string.
s1 U 0abc09
s5 U 0+yR09
strcatIs1Es5J9 // s1 = "abcxyz"
%trc'&+$ir%tK%econd,
Compares the first and second strings. #f the first string is greater than the second one then a
nmber higher than 0 is retrned. #f the first string is less than the second then a nmber lower
than 0 is retrned. #f the strings are eAal then 0 is retrned.
s1 U 0abc09
s5 U 0abc09
i U strcmpIs1Es5J9 // i = 0
%trlen+%trin",
Retrns the amont of characters in a string.
s U 0abcde09
i U strlenIsJ9 // i = 5

Das könnte Ihnen auch gefallen