Sie sind auf Seite 1von 13

c programming an introduction

welcome to the nifty world of c programming. well i'm starting the


whole thing from basics my friends and it will be ok for most of u. not
only will these tutorials be a little more indepth , but it will also cover
all the imp aspects.

history of c

"hey dennis, why don't you make a programming language for unix."
"okay brian, but you have to help me write the book for it."
"no problem man!"
"pass the twinkies my brutha."
"dude i think we're out of twinkies."
"what!!!! you mean to tell me that here in bell labs, where we created
the transistor, unix, and the 10 cent a minute long distance dialing
plan we can't keep a steady supply of twinkies!"

c was brought to us by those fine people at bell labs. you know those
at&t people? they had themseves this operating system called unix,
that needed a programming language. they made it, and since the
previous version was called b, they decided to call it c for obvious
reasons. no, there was never an a programming language. i say that so
you won't embarass your self on an irc, dang those guys can be brutal.
it was written by this guy named dennis ritchie. the b in b stood for bell
by the way. so if your ever on jeapordy, now you know.

the workings of c

c is a compiled language. in your cooky compiler it takes the c "code"


that you write and breaks it down into these itsy, bitsy, teenie, weenie,
1's and 0's. this is what the computer understands. 1's and 0's. this is
called machine language.

i still find it amazing that for all the power that a computer has it's just
working off a base 2 number system. wouldn't it be different if humans
used base 2? in the lottery you'd only have 0 and 1 too choose from.

after you compile your source code a thing called an object file is
created. afterwards, if it is brave and it's heart remains pure it is ran
through the linker which turns it into an excecutable file. let's write a
simple c program shall we? don't worry if you don't understand
everything i'm about to say. just copy the source code, i'll break down
all lines of code. do not use capital letters!!!!!! !! do not copy and
paste this code!!!! the < stdio.h > is confusing to your browser, since it
looks, smells, and tastes like an html tag. i had to use some spaces. so
if you cut and paste it will not work!!! so there!!!!

important :

now for compiler you can use many c compilers avaiable in market but
i would like to recomend borland turbo c ver 3.0. a simple program
with lot of help and easy to use interface .

i would expect that you wont be haveing any problem installing


compiler or running it.

now if you have to stroe a c code some where stroe it in .c format .cpp
is fine too but it will start causing problems later so better to be
warned in time......

now lets think that you had done every thing regarding compiler and
lets get down to the code .......

#include < stdio.h >


#include < conio.h >

main ( )
{

clrscr();
printf ("goodbye cruel world!!!!");
getch();
}

compile and run. you should get something like goodbye cruel world!!!!
on your screen.

1st line
#include
this stdio.h stands for standard input output header. basically the code
is "telling" your computer to use a certain command that is found in
the stdio.h "file". there are a lot of "#include" files and they all have
these wild commands in them, that you can access using the #include
thingee.
2nd line
main ( )

this is the main function. there are many functions and all will have to
do battle to be worthy of the title main. okay all joking aside, in c you
can have a lot of different functions. these can be titled; main ( ),
function1 ( ), function2 ( ), and so on. what you have typed has but one
function in it that will do your bidding. it's really not important that you
know all of this in your infant stage, but i mention it anyways.

3rd line
{
this is the all important curly bracket. it is used to seperate "blocks of
code" from each other and keep them from fighting each other. just
kidding.

4th line
printf ("goodbye cruel world!!!!");
this is the printf command. it "hides" in the stdio.h file and waits to be
called. and now in this line we use it. the printf commands stands for
"print format." it is not print function as some believe. it bascially takes
the text within the quotation marks and displays it on the screen. "hey
digital you used capitals." arrrgghh caught red handed. it won't affect
c's case sensitive nature if you use it in this case. "why does it display
on the monitor digital?" well son, way back in the day before monitors
they used teletype (ancient printer) machines to display stuff from the
computer. no games back then, too much paper. all printf does is take
the stuff you want written and puts it on the screen. you must enclose
what you want written on the screen in quotation marks and
parenthesis! you must also end the line wit a semi colon! do not
question it, just do it!

6th line
}
you are enclosing your block of code so it won't get into a fight. just
kidding. here is where you end this block of code.

so now you've written your first c program. compile it and run it. bask
in the glory of your accomplishment. savor this moment young jedi for
things get a whole lot more complicated in the future.

"say digital what if i have more to say?" good question. 1 line


sentences just aren't sexy in our complicated world. let's add a second
line of text by using the newline escape character.
#include < stdio.h >
#include < conio.h >

main ( )
{

clrscr();
printf ("i live in pakistan!!!!!!\n");
printf ("my father is pakistani \n");
printf ("i m proud pakistani");
getch();

so here you go. compile this bad boy and run it. you should get a
similar output, but with 3 lines of text. whenever you use a front slash
the compiler says, "oh my gosh and escape sequence!!!" the printf
ignores the n, cuz it has been identified in such a manner.
ahhhh, the assertation of knowledge. weeeeeeell, that's all for now
folks! i'll see you wacky internet people later - digitalscribe

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

variables

greetings c people welcome to the 2nd installment in my soon to be famous c tutorials.


we will be going into variables in this section. variables are veeeery important in
programming. pay close attention to this chapter kiddies for it you won't get by without it.

what is a variable?

we all know how to add right? 2+2=4? suppose for an instant though that we wanted
write a formula on how to add to someone who had no concept of it. we could right it as
a+b=c.

now any one can substitue numbers in the place of a,b, or c. "let's see a = 3, b = 4, so c
will equal 7!!!!, you can plug any formula you want into a computer;like ohm's law e=ir,
etc. i know that last sentence wasn't necessary i just want to impress people with the fact i
know ohm's law.

all a variable is in our field is just a place set apart in a computers memory to hold a
changing value. this is very useful, for it helps those hard working scientists do complex
math, leaving plenty of time to eat , drink and watch " kabhi khusi kabhi ghum " . now
don't shriek when you see all these numbers, doing math is simple with computers
because the computer does all the work!

types of varibales

there are many different types of variables.

each "variable type" has a different range of values. you can only fit oh so much stuff into
one variable type! here are 4 of these variable types;

int - interger/ range = -32768 to +32767/ storage required = 2 bytes

long - long interger/ range = -2147483648 to +2147483647/ storage required = 4 bytes

float- floating point interger/ range = 3.4*10ex38 to 3.4*10ex-38/storage required 8 bytes

it's not a necessity that you memorize these types just yet. i recommend that you learn
them through use. to use variables in this section, we will be using the scanf command.
the scanf (scan function) basically reads your keyboard for a specific type of input. it
stops scanning when you press the enter key. i'll explain more after you write the
program.

we'll also using c's operators. that is + for addition, - for subtraction, * for multiplication,
and finally / for division. we will first write a program that squares a number. let's code
shall we? type this program into your c compiler;

#include < stdio.h >


#include < conio.h >
main ( )
{
clrscr();
int x,y;
printf ("enter a number and i'll square it!!!\n");
scanf ("%d", &y);
x = y*y;
printf ("%d is your number squared!!! hahahaha!", x);
getch();
}
compile it and run it. remember to not click and paste!!!!

let's breakdown lines 4,5,6, and 7 of the above source code.

line 4

int x,y;
in this line we are declaring our variables. we are basically making the little sections of
memory in this line of code. so here we have 2 'boxes' called x and y. they are integer
variables ready to put their talents to work for you.

line 5
printf ("enter a number and i'll square it!!!\n");
just a printf statement that asks a question.

line 6
scanf ("%d", &y");
this is where scanf is used. the %d is what is called a place holder. we'll get into it's
signifcance later. the scanf function here was patiently waiting for you to enter a number.
when you pressed enter it took that number and "threw" it into the y variable. that is why
you had to type in the &y. soooooo now we have a number sitting in the little y box.

line 7
x=y*y;
this tells your computer to do some number crunching. it takes what is in the y variable
and multiplies it by itself. afterwards, it takes that number and throws it into the x
variable. so now we have the answer sitting in the x variable.

line 8
printf ("%d is your number squared!!! hahahaha!", x);
okay it's a printf statment with some subtle differences. the %d is a placeholder as said
before. %d is specifically used for int variables. used in printf it will display the variable
that you stored in x. at the end of the quotations and comma you see x. this basically
'tells' your compiler the x variable will be displayed in the %d place holder. put y in there
instead and see what happens.

play around with the different math functions. remember that c does math backwards. ie;
4=3+1.

you know what though? if your just using int, it will not work with everything. case in
point;

#include < stdio.h >


#include < conio.h >
main ( )
{
clrscr();
int x,y;
printf ("enter a number and i'll reciprocate it.\n");
scanf ("%d", &y);
x = 1/x;
printf ("%d is your answer.",x);
getch();
}

compile it and run it. when it asks you for a number enter 2. for those don't know the
reciprocoal (a number divided into 1) of 2 is 0.5. press enter and you should get
something cooky. it will not work. the int variable will not work well with anything other
then whole numbers. what to do? what to do? real c programmers don't panic and move
to montana (unlike pascal people), they find another way!!! that last sentence wasn't
necessary, i'm always searching for new ways to annoy people with my unique brand of
dry humor. try using a different variable type. in this case use float. retype this into your
compiler;

#include < stdio.h >

#include < conio.h >


main ( )
{
clrscr();
float x,y;
printf ("enter a number and i'll reciprocate it.\n");
scanf ("%f", &x);
y = 1/x;
printf (%f is your answer.", y);
getch();
}

it should work now. i'll tell you how to fix those annoying decimal place 0's later.

i guess thats enough for today but any ways try different airthematic operators by your
self and do tell me if u have any problems ........ bye for today....

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

variables 2 the search for char...

okkk jeee first of all thanx to all those who appriciated the small efort i
had made and yes to all those who want to learn java and vb .......not
now but soon i will be going after those languages too.... the fact is
that i want that we should start from basics like c and c++ and then
we can even take it to vc++ or vj++ coz these are the two languages i
basically work in ..............

but this can be just a revision for u before we take some bigger steps
.....any ways lets continue ......

however, it's 2 a.m. right now so i'm not so sure if i'll botch this up
again. anyways in this section we are going to discuss the char
variable. char stands for character. as the name suggests this "variable
type" is used to store characters. whether these be single letters,
words, or other stuff.
type this fine piece of c code into your compilers.

#include < stdio.h >

#include < conio.h >

main ( )
{
char name[5];
printf ("hey what's your name? \n");
scanf ("%s", &name);
printf ("only kings are named %s", name);
getch();
}

compile it and run it.

hahahahahahaahahahahahahhahaha...a good laugh is had by all.

anyways it is basically the same concept as the variables we worked


with before only it uses a char variable type. look intently at the 4th
line of code. here we have "declared" a char variable and named it
name...bleh a half hearted attempt at humour this early in the
morning.

the number enclosed in the brackets is the space in the computer's


memory that we have set aside for it. besides that it isn't too different
from all the stuff we've working with in variables.
the getch ( ) function

now we get a little bit more complicated. the getch funciton basically
works like this. it waits for you to press a key and stores that key.
confused? type this tidbit into your compilers and run it

#include < stdio.h >


#include < conio.h >
main ( )
{
char key;
printf ("press a key \n");
key = getch( );
printf ("hey you pressed the '%c' key!!!", key);
getch();
}

depending on what kind of compiler you use the source code might or
might not work. if not try putting a getchar instead of getch. you see a
new include directive, conio.h. this is where the getchar function is
stored and when you type it in it retrieves it for you. the getch function
waited for you to press a key and stored that key into the variable
named key.

key = getch ( );

after it is stored in the key variable you displayed using the printf
function

printf ("hey you pressed the '%c' key!!!", key);

notice the %c placeholder. this is used for displaying a character. this


single quotation marks around the %c key is important so don't forget
them.

if you haven't done this already try and change getch to getchar and
see what happens. it's basically the same thing only it waits for you to
hit the return button.

let's modify this source code to give us ascii values.

#include < stdio.h >


#include < conio.h >
main ( )
{
char key;
printf ("press a key \n");
key = getch( );
printf ("hey you pressed the '%c' key!!!\n", key)
printf ("don't you know its ascii value is %i!!!", key)
return (0);
}

well in this here example, the same concept is applied as the one
before. we added a printf line that placed contents of the key variable
into the %i place holder.

doing this tells you the ascii value of that key.

there is much more about the char variable that will be covered, ie;
putchar and so on. however i will these later. so come back soon and
be amazed at all the mighty attributes of the char variable.

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

variables part 3

even more c to brighten your day!!!

welcome to the next little diddy on char.

if you recall in last lecture we went into a little tidbit on char. there is much more we can
learn from char variables and we will start this marvelous learning process by typing
code. enter this into your compilers and run it!

#include < stdio.h >


#include < conio.h >
main ( )
{
char key;
printf ("enter a key!\n");
key = getche( );
printf ("\tyou pressed the '%c' key!!!", key);
return (0);
}

this is basically some of the same stuff we've done before and only it containes the getche
function. it produces the same kind of effect as getch, only it displays immeadiately what
you type. to help you distinguish between the two imagine that e at the end of getche
stands for echo. wait a minute! i wonder if it really does stand for echo? hmmmmm........

i know in the last tutorial i said i would cover putchar ( ), but i think i'll hold off on that
until we get into loops. i do that because the programs i use to discuss loops uses putchar
a lot...that and the fact that i'm extremely lazy. anyways we let us now discuss constants.
don't worry if the discussion on variable seem a bit scanty, as i go into further tutorials
variables will also be used a lot and discussed plentifly.

behold constants in all it's mighty glory!!!

constants are extremely easy to comprehend. it almost works like variables in that the
computer sets aside memory for values, but it is different in that these values are defined
and set in stone. these values will not change. they refuse to compromise. they are not
human. they cannot feel pain. they cannot be reasoned with............sorry. type this into thy
compiler and run it

#include < stdio.h >


#define tax 10000000
main ( )
{
float x,t;
printf ("how old are you\n");
scanf ("%f",&x);
t = x*tax;
printf ("you have insulted the mighty tax dept you owe %.0f rupees!", t);
return (0);
}

we've done this type of program before. the only real difference is the #define tax thingee
and the placeholder %.0f.

#define tax 10000000

so here you are creating a constant called "tax." you assigned a value to that constant
10000000. this will stay "constant." this will not change. you will not assimilate it. it will
resist. it isn't hum...bleah sorry. anyways it's going to stay the same.

printf ("you have insulted the mighty tax dept you owe %.0f rupees!", t);

remember a long ways back when i said i would tell you how to get rid of the decimals in
float? well there you go. by placing a 0 in behind the decimal point you are telling the
computer to ignore everything next to the decimal. if you wrote a %.2f it would take it
out to two decimal points.
well thas it for constants and variable for now will start loops and then move to some
advance concepts of array and strings.

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

loops

in this chapter we are going to do a simple for loop. it's really quite
simple, and it's not as hard as some might think. well let's begin;

#include < stdio.h >


main ( )
{
int i;
for (i=0; i<100; i++)
{
printf ("oh your so fine, your so\n");
printf ("fine you blow my mind \n");
}
return (0);
}

well here we have some stuff that on the surface may seem a little
deep but really it's not. almost everything in the preceding block of
code should be obvious, except for line 5 and 8 and whats in between.
let's look at line 5 shall we?

for (i=0; i<100; i++){

the for keyword is the what sets up the loop. everything between the
parenthesis (the argument) is what sets up the parameters of the loop.
above this line of code you see that an int variable was set up. in the
for loop we have (and i realize i'm being redundant) set the parameters
of that variable. let's look deeper and explain the argument.

i=0;

here we have set the i variable to 0. this is the initialazation of what


will be a "sort of" counter.

i<100;

here we have set the condition of the loop. this says that the loop will
cycle as long as i is "less than" 100. as soon as i is equal to 100 than
the argument is not less than 100 and it will stop. i guess you realize
that i'm using the word argument a lot. it's basically programming talk
for parameter.

i++

this increments(makes it move up one digit). it tells i to basically


continually move up

anyways to put in pseudo code;

for (start count at 0; set it go 99 times; make i go){

now that we have explained all that lets see how that little snippit of
code relates to whats between the for brackets ({ }). let us employ our
abstract thinking shall we? now this is just an analogy of sorts, don't
take it literally. not all analogies are perfect!!!!!

si in short the two print f statements will be printed around 99 times


and thats all....

whew!!! that was a mouthful!!

a note on the incrementing thing. if you wanna use it to decrement you


would use i--. however don't use it on what we just wrote....that would
be screwey hehehe. anyways i'll write some more stuff on loops later,
i'm getting tired.

Das könnte Ihnen auch gefallen