Sei sulla pagina 1di 29

C Basics

#include <stdio.h> #include <stdlib.h>

This is what's called a pre-processor directive. What this does is tell the compiler that you are going to be including the standard input output functions in the C library, the .h tells the compiler that it is a header file. The stdandard library is another header file you will need often. This will be in every single program you write with C so do your best to remember it. Our next line is also going to be something that we will always need hmmm how did it go again oh yes!
int main() {

The int just stands for integer why is integer even there? Well you are telling the program that when you are done with main that you will return an integer, you will see soon enough. Main is simply the name we are giving it although it does have to be main so don't go and get creative and change it. The () is also something that has to be there even if you aren't planning on putting anything in them, only in more sophisticated programs will you put something in them. Last is the curly brace { it's best to look at these as beginning and end, the { symbol being the beginning and } symbol being the end, I haven't put the ending ones yet because we haven't finished main, which brings us to our next line of code.
printf("My first program! Oh and hello world\n");

Printf means that you want to literally print something to the screen whatever is inside the quotations is what will print. The \n is just an escape sequence, whenever you put one of these it will skip to the next line, very similar to when you push the enter button while you are typing. After the parenthesis you need a semicolon, this is mandatory for a statement and all printf functions don't forget it, without it your program will not run. Also last thing, remember the standard input output pre-processor directive well by us declaring that we are able to use printf since it is output. <
system("pause");

System pause is simple all it is doing is pausing the program giving you time to see what has been executed so far just remember to put the pause in quotes and parenthesis and end it all with semicolon.
return 0; }

Remember when I said we put int for integer before main because we would return and integer well here it is we are returning 0, this means everything went according to plan. Now that we are finished with main we can end it with a }.

#include <stdio.h> #include <stdlib.h> int main() { printf("My first program! Oh and hello world\n"); system ("pause"); return 0; }

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- **********--------------------------------------------------------------

C Datatypes
Commenting is something that is used commonly in a program, /*This is a comment*/. When anything is put in between those two symbols it is disregarded by the compiler, commenting is used to provide clarity to other programmers or even yourself at times. So when you see this know that this isn't part of the code just a comment explaining the code, by the way, I will always put comments in a different color to provide clarity. Using data types is something that you absolutely need in a program so let us not waste anytime talking about them.
int x;

What I just did was declare a variable called x. Int is short for integer and x is the variable I declared. Now right now x is unassigned but that doesn't mean nothing is stored in it. Right now there is what we call garbage in the variable, some crazy number that nobody would usually use. How do we fix this? All we have to do is assign it a value.
x=5;

Now for the rest of the program (unless we say otherwise) x is assigned the value of 5. Notice I didn't have to put int in front of x again, this is because we only do this when we are declaring a variable, after we declare a variable we can just call it by its variable name. So now that x is equal to 5 lets see what we can do with it.
printf("%i",x);

Whoa! What is that? We already know what the printf function does but what about that %i? This is placeholder for x, the % symbol is what is going to hold x and the i symbol is just telling it that x is an integer, i for integer not to hard to remember. The next thing is the x after the quotations don't forget the coma it's telling the compiler that the very next thing you put is what you want to go into %i, in this case x. Don't forget to end it with parenthesis and that pesky little semi colon. Okay now lets put all the code together into a single program!
#include <stdio.h> #include <stdlib.h> int main() { int x; x=5; printf("%i\n",x); system ("pause"); return 0; }

So it prints out a 5 big whoop lets see what else we can do. What if we wanted to take the variable x and times it by something say another variable. First we will declare another integer alongside x.
int x,y,z;

Notice how I declared x,y,z as integers all in one line of code we could have also declared them in three separate line but lets be lazy and do it this way. I will initialize x to be 5 again and y to 3. So the x and y is what we will be multiplying and z will hold the product of the two, like this.
x=5; y=3; z=x * y;

Notice how x and y aren't together like xy. In math class this means multiplication but computers are different, they won't know what the heck you are talking about. Now that we have z lets print it out.
printf("%i",z);

Don't forget the place holder and the i since z is an integer. So you may already be thinking what if you wanted to multiply 5.2 and 3.7 would it make a difference? Yes, it would make a big difference as a matter of fact. The value z would truncated, meaning some of it's value would be cut off. Don't fear, we have a fix.
double x,y,z;

The data type double is used to hold decimal type numbers, this way they will hold their true value even if used as a decimal.
x=5.2; y=3.7; z=x * y; printf("%f",z);

If you were paying close attention you probably noticed a %f instead of %i, no this wasn't a typo this is what holds a double data type. It doesn't really make sense like the i and integer does but it is what it is try to remember it, there were countless of times when I couldn't figure out why my program wasn't working correctly and it turns out all it was was this simple mix up. Also we could have used double to just multiply 5 and 3 instead of using integers. It would have multiplied 5.0 and 3.0 which technically isn't any different. So why ever use integers if you can always just use doubles. The answer is space, using double data types takes up more memory than integers thus resulting in a loss of speed. In a small program it's impossible to notice the difference but in larger more sophisticated programs memory becomes more important. There are many other data types that you can use but to keep complexity at a minimum they won't be covered. If you are curious however a couple more for integers are long and short. For double there is float and long double,there are still more but these are the more used types. There is also a char type which is used for chararcter data types but we'll hold off on that for now. So until now we have been restricted to initializing data within the program. What if we wanted x to be 6 or 8 or 184. It is to much of a hassle to have to alter the source code within the compiler wouldn't it be easier to just initialize a variable while the program is running? This is possible through the scanf function.

scanf("%i",&x);

What the scanf does is pause the program and wait for a value to be put into the variable. This is similar to the printf output with the %i for integers the only difference is the ampersand symbol before the x. What the & symbol does is take in the address of x in order to manipulate it don't forget this small but important step when using scanf. How about a sample program?
#include <stdio.h> #include <stdlib.h> int main() { int x; double y,z; printf("Please enter a value for x and y "); scanf("%i",&x); /*scans in a x/* scanf("%lf",&y); /*scans in a y*/ z=x/y; /*z equals x divided by y*/ printf("%i divided by %f is %f\n",x,y,z); system ("pause"); return 0; }

The reason why I made y a double data type is because whenever you try to divide two integers that don't divide into eachother evenly your answer will be trucated to zero. For example 3 divided by 2 is 1.5 but 1.5 is not an integer. However, in C when two numbers are being divided and if atleast one of them is of the double type the other will be automatically promoted to a double type just for that calculation. Another thing to notice is whenever your scanning in a double variable be sure to put %lf not just %f. Go ahead and copy this code and see how it works. Notice how when the answer is displayed it has a lot of decimal places, if you don't like the way this looks there is a simple fix. On the printf("%i divided by %f is %f\n",x,y,z); line just go ahead and put a .1%f where you see %f. What this will do is display y and your answer which is z to the first decimal place, if you were to put a .2 they would displayed to the second decimal place and so on. Also notice in the printf("%i divided by %f is %f\n",x,y,z); line I printed out x,y,and z at the same time. Whenever you do this be sure to put the variable in the right order. For instance, x goes into %i because each one is displayed first %i is the first placeholder in the quotes and x is the first variable after the quotes. Now that we have these new founded tools we can write a more interesting and useful program. In the United States the unit of speed is miles per hour, but in many other countries they use kilometers per hour, wouldn't it be nice to build a simple program to convert mph to kph? Well we already have all the tools we need all that's left is a formula. One mph equals 1.609344 kph. So y=1.609344*x, x being our input in the program.
#include <stdio.h> #include <stdlib.h> int main() { double x,y; printf("Please enter a speed in miles per hour\n");

scanf("%lf",&x); y=1.609344 * x; printf("The equivalent speed in kilometers per hour is %.2f\n",y); system ("pause"); return 0; }

So there you have it simple but useful. Now what if you wanted a program to convert for kph to mph. It would be hassle to actually have to alter the source code. Wouldn't it be convenient to be able to choose what conversion you would like to do while the program is running? Do I ever end a question without an answer? The answer is yes, by giving the program the ability to think for itself (to a certain extent, I'm sure we have all seen terminator 2).
-----------------------------------------------------------------***************-------------------------------------------------

C Conditions
Condtions allow a program to think for itself. Many times there will be moments when you want your program to decide from different options depending on the input you give to it. This allows your program to have much more diversity, without conditions, your program would run the same way everytime and what's the fun in that? There are a few different conditions that are used if, if else and else. Here is the syntax for an if statement.

If Statement
if(x > y) { printf("x is greater than y"); } So if x greater than y do the stuff you want it to. The curly braces aren't necessary in this example because there is only one line of statements but if there were more it would be required. You still can put the curly braces just to be safe so it's entirely up to you. If there are more than one if statements you'd like to use than you can use the else if statement

Else If Statement
else if(y >x) { printf("y is greater than x"); } Other than it be calling an else if, this statement works the same way as an if statement yo do however, have to use an if statement first in order to use an else if. So what if x wasn't greater than y and y wasn't greater than x than we would want the program do to something else well that's exactly what the else statement is for.

Else Statement
else { printf("x and y are equal"); } The else statement is basically "This statement isn't true and this other statement isn't true so do this." I printed x and y are equal because if neither are greater than or less than one another than they must be equal. One thing I do want to point out is this. if (x==y) { printf("x and y are equal"); } Notice the two equal signs, what this means is to check for equality where one equal sign means assignment, x=y, x is equal to y, in comparison to, x==y, check to see if x is equal to y. Okay so lets check out a complete program using the if statement. #include <stdio.h> #include <stdlib.h> int main() { double x,y; printf("Enter a value for x"); scanf("%lf",&x); printf("Enter a value for y"); scanf("%lf",&y); if (x > y) { printf("x is greater than y"); } else if (y > x) { printf("y is greater than x"); } else { printf("x and y are equal"); } system ("pause"); return 0; }

Notice how the last statement, the else statement there is no condition. This is because it doesn't need one, the condition for the else statement is if the other if conditions aren't true than do this. There are number of other operators that you can use with an if statement, these are a few. (x > y) "x is greater than y" (x >= y) "x is greater than or equal to y" (x < y) "x is less than y" (x <= y) "x is less than or equal to y" (x==y) "Check to see if x is equal to y" (x != y) "x is not equal to y" ---------------------------------------***************-------------------------------------------------------

C Booleans Operators
Some other useful operators are called boolean operators which are and, or, and not. When I first learned these I didn't see how I would ever put these to use but now it seems I use these in almost every program I write. What the and, or, and not operators do is give your program much more versatility. First lets take a look at the and operator. Instead of using x and y I'll put actual numbers in them so you can see them more clearly.
if(2 > 1) && (5 > 3)

The and statement requires that both conditions be true in order for the if statement be true. So what this is saying is if 2 is greater than 1 AND if 5 is greater then 3 than the if statement is true and execute whatever command, both statements are true so the entire if statement is true, now lets look at one that isn't true.}
if (2 < 1) && (5 > 3)

Now what this statement is saying is if 2 is less than 1 and if 5 is greater than 3 than the if statement is true but it is not true. 2 will never be less than 1. Both statements have to be true in order for the whole statement to be true. Let us take a look at the or operator. <
if (5 < 3) || (7 > 6)

This or statement is true and will execute. This is because unlike an and statement an or statement requires only one to be true in order for the entire if statement to be true. 5 is not less than 3 but 7 is certainly greater than 6 so the or statement will execute. Last there is the not boolean operator.
if !(2 > 1 && 5 > 3)

Looking back we can remember that this is an and statement and that it returned true. However this statement will return false, this is because of the exclamation mark (which is the symbol for not) what this operator does is return the opposite. If the statement were false it would return true but in this case the statement is true but it ultimately returns false. So lets check out a simple program that uses the boolean operators.
#include <stdio.h> #include <stdlib.h> int main() { int x; printf("Please enter your age"); scanf("%i",&x);

if (x > 19) && (x < 30) printf("You are in your twenties"); else printf("You are not in your twenties"); system("pause"); return 0; }

This program is very straight forward, it contains an and boolean operator. The program asks for your age and tells you if are in twenties or not, not the most useful program but it gives you a clear example on how to use these things. The and operator checks to see if x is 20 through 29 if so then it prints out you are in your twenties and if not it will print out you are not. Now remember that program that converted from mph to kph, referring back to what I mentioned earlier about having the option to choose from within the program to convert from mph to kph or from kph to mph. This is made possible with just a simple if statement, here is the code.
#include <stdio.h> #include <stdlib.h> int main() { int z; double x,y; printf("Enter 1 for MPH to KPH or 2 for KPH to MPH\n"); scanf("%i",&z); if (z == 1) { printf("Please enter a speed in miles per hour\n"); scanf("%lf",&x); y=1.609344 * x; printf("The equivalent speed in kilometers per hour is %.2f\n",y); } if (z == 2) { printf("Please enter a speed in kilometers per hour\n"); scanf("%lf",&x); y = x/1.609344; printf("The equivalent speed in miles per hour is %.2f\n",y); } else { printf("Invalid input\n"); } system ("pause"); return 0; }

Now lets break down this code in comparison to the other code that just took in mph and converted it to kph. Immediately you will notice that another variable was declared, integer z. z will be used just to determine what calculation to do. So if a user were to enter 1 for z the

program would pass control to everything in the curly braces of the if statement that check to see if z equals 1. If a user wants to convert for kph to mph than they would enter 2 passing control to everything in the curly braces of the if statement that checks to see if z equals 2. Notice the else statement, this is sort of the default statement in this program, remember that else is everything else z can possibly be, so if z is not 1 or 2 than the user must have entered something else, the program will print invalid input and end. Try typing this code and running it, I encourage anyone to play around with it and see what they come up with it. ------------------------------------------*******************----------------____-------------____-----

C Switch Statements
Switch statements are special conditional statements that are sometimes easier to use than an if statements. A switch statement is often used in a menu driven program where a user would make a selection according to their needs. Here is how a switch statement looks.
switch (variable) { case 1: do stuff; break; case 2: do stuff; break; default: do stuff; break; }

There can be as many cases as you want, I just happened to put only two for simplicity. After every case there must be a break statement (we will talk more about breaks in the loops lesson) in a nutshell, a break will take you out of the switch and on with the rest of the program. A case is similar to an if statement, case 1 is checking if the variable is 1, if so it will execute everything before the break, case 2 is checking if the variable is 2, and so on. Also notice how there is a colon after the case not a semicolon. Once you are done with your cases you must use a default, this is similar to the else statement, the default is basically saying if not case 1 or case 2 then this. Now lets take a look at a program using a switch statement.
#include <stdio.h> #include <stdlib.h> int main() { int z; double x,y; printf("Enter 1 for MPH to KPH or 2 for KPH to MPH\n"); scanf("%i",&z); switch (z) /* the variable z will be checked for each case*/ { case 1: /* case 1 replaced the if statement that checked to see if z was equal to 1*/ printf("Please enter a speed in miles per hour\n"); scanf("%lf",&x); y=1.609344 * x; printf("The equivalent speed in kilometers per hour is %.2f\n",y); break;

case 2: /*case 2 replaced the if statement that check to see if z was to 2*/ printf("Please enter a speed in kilometers per hour\n"); scanf("%lf",&x); y = x/1.609344; printf("The equivalent speed in miles per hour is %.2f\n",y); break;

default: /*default replaced the else statement*/ printf("Invalid input\n"); break; } system ("pause"); return 0; }

Something important to note, remember how in every conditional statement that had more than one line it was required to put them in curly brackets, here is to refresh your memory.
if (x>y) { do stuff; do more stuff; }

A switch statement works a little differently, instead of putting curly brackets for each case you instead put only one set of curly brackets for the whole switch statement. The reason why you do not need curly brackets for each case is because of the break. The break is indicating that the case is done (which is what usually the curly brackets are for).

IMPORTANT!
Unlike condtional statements you cannot use cases exactly the same way, remember how you can use an if statement to check for more than one situation such as.
if (x <= 10); /*This is saying to execute the statement for all values less than or equal to x.*/ case: (x <= 10) /*DOES NOT WORK*/

Cases have to equal an exact value such as 1,2,3, and so on, cases can't have condtions. This is where conditional statements offer a lot more flexibility in program. ________________*********************************___________________________

C Loops
Loops are many times the very heart of a program. They allow programmers to execute the same code a given amount of time. Loops, when used the right way can be very powerful programming tools. There a three loops that we will look over, the first is called a while loop, here is how it looks.

While Loop
while (condition) { do stuff; increment variable; }

(condition) would be something like (x < 5) and the increment variable (in this case x) would look like x++, this would increment x by one every time the loop executes. Sometimes looking at code when it is described more in general (like how it is above) is actually more confusing than seeing an actual program, let us wait no more.
#include <stdio.h> #include <stdlib.h> int main() { int x=0; while(x < 5) { printf("%i\n",x); x++; } system ("pause"); return 0; )

First notice how when I declared x I also initialized it to 0 in the same line this is legal and is perfect for lazy programmers like me! The while condition check to see if x is less than 5, well we just initialized it to 0 so of course it is. This allows the program to run through the loop and print out x (which is 0 right now) and increment x by 1. Now x is 1, the while condition checks again to see if x is still less than 5 and in this case it is. The command once again is to print out x (which is now 1) and then increment x by 1. Now x is 2, do you get the picture? All this program will do is print out 0,1,2,3, and 4, once x is 5 it is no longer less than 5, so the loop breaks and control is passed to the next command which in this case is to end the program. Not the most exciting program but hopefully this gives you a good idea what loops are all about.

Do While Loop
do { x=5; printf("%i",x);

x++; } while(x < 5);

I know before you say it, this almost looks exactly the same and you are right but there is one significant difference. This is called a do while loop, the difference between the do while and the while is that the do while will execute at least once no matter what. This is because before checking the condition the code executes then the condition is checked last (notice the condition is the last thing printed). If we were to initialize x to 5 in the while loop program then the loop would have never ran and the program would just end. However, the do while will run once and once it checks the 5 is not less than 5 then the loop will not execute and the program will end. At first it's hard to see why someone would want a loop to execute at least once even if the condition isn't true, but trust me there will be moments when this little tool does just the trick. ALSO! Notice the semicolon after the do while condition, this is necessary however, when it is a while loop you do not put a semi colon, kind of tricky but it's just one of those things. The last kind of loop is called the for loop. This loop is the most commonly used probably because of it's clarity and versatility. I will write the same program as the while loop but using a for loop instead.

For Loop
#include <stdio.h> #include <stdlib.h> int main() { int x; for(x=0; x<5; x++) /*This is a for loop*/ { printf("%i\n",x); } system("pause"); return 0; }

Notice how the for loop is more clean and precise. The first thing you must do is initialize the variable x=0, then the condition while x<5, last the increment x++, also make sure you separate each with a semicolon. As you can see there is nothing new just the format, it is all in one, this is why it is commonly preferred. Also be sure to close the loop within curly braces as you would an if statement, this is required. Okay now lets check out a little more interesting program using loops. This program will print out a table of trigonometric functions from 0 to 360, for all of you who have taken trig you may appreciate this program a little more than those who have not. Also, if trig was one of your lesser favorite subjects I apologize in advance for boring you to death. NOTE! There are a few new things I have to introduce at once however, I will do my best to explain them.
#include <stdio.h> #include <stdlib.h> #include <math.h> /*This is another header file, inlcude this one you are using more advanced math*/ #define PI 3.141593 /*Defines PI, read below for more info*/

int main() { int x; double r; printf(" printf("Angle(deg)

Table of Trig Functions\n\n"); Sin Cos Tan\n\n");

for(x=0; x<=360; x+=15) /*x will start at 0, increment by 15 every loop until it is equal to 360*/ { r= x * PI / 180; /*Degrees must be converted to radians in order to calculate the trig functions*/ if( x==90 || x==270) /*If x equals 90 OR 270 print out the sin,cos,and undefined for tangent*/ { printf("%3i %13.4f %13.4f Undefined\n",x,sin(r),cos(r)); } else /*Otherwise calculate and print out the function of sin,cos,and tan*/ { printf("%3i %13.4f %13.4f %13.4\n",x,sin(r),cos(r),tan(r)); } } system("pause"); return 0; }

Whew that was fun! Guys? You still there? Okay so let me break down this code. The first new thing is the header file math.h, this is used because we are using more advanced math like sine,cosine, and tangent. When we are using add,subtract,multiply, and divide, we don't need this header file. For things like square root, absolute value, exponents, and other advance mathematics we have to include the math.h header file. The next new thing you may have noticed is that #define PI 3.141593, this is a useful tool, whenever you are going to be using a certain constant continuously in your program it is helpful to define it with a keyword, #define is how you call upon this tool, the next thing is what you want to name it, in this case PI, the last thing is what PI holds 3.131593. Now whenever I need to use 3.141593 I simply just type PI in its place. The printf statements may look weird to you, the blank spaces are simply just spaces so it looks more like a table rather than a whole bunch of numbers that are right next to each other. The for loop sets x to 0 and won't stop until it equals 360 incrementing by 15 degrees every loop. This way we will get the sin,cos,and tan every 15 degrees all the way up to 360 degrees. The r=x*PI/180; is the formula to convert degrees to radians, the thing is, with C it can only calculate the sin,cos, and tan in radians not degrees, therefore we have to convert. If you remember back to trig you may remember how tangent is undefined at 90 and 270 degrees, therefore once x is equal to 90 or 270 we want it to print out the sin and cos as it usually would but print out the tangent to be undefined. Otherwise (the else statement) print out the sin,cos, and tan. Remember that the %13.4 means 13 spaces before the number the 4 mean to 4 decimal places. You could just put %.4f but then the numbers would be closer together and it wouldn't look so much like a table There are two keywords that you must know when using loops. These keywords are break

and continue. What the keyword break does is break you out of a loop in a special circumstance that you would specify. Here is an example.
int x=1; while(x<=10) { printf("Hello! We are in a loop\n"); if(x==7) break; /*This is how you use a break*/ x++; }

The while loop is intended to loop exactly ten times however, the if statement specifies that when x is equal to 7 to break out of the loop. Since this break is here the loop will ultimately only execute 7 times. Breaks can be very useful in times when you want the loop to stop in special circumstances. Continue is another keyword used in looping in special circumstances it is convenient to be able to not execute a certain line or lines of code but not break you out of the loop entirely. Unlike break, continue doesn't take you out of the loop entirely, what continue does is skip the rest of the loop and start from the beginning. _______________________************************______________________________

C Functions
Quick Note
Functions are very powerful programming tools that is used in almost every program. Functions allow programmers to break up code into different jobs and test those functions individually. In other words, instead of having hundreds or even thousands of line in your main program (int main ()) you can have different functions and call upon them whenever you desire. The best way to learn is to do, shall we?
int my_function(int n)

Here is what a function looks like. The first int is telling what data type will be returned just like how we put int main. My_function is just simply the name of the function, I could have called this anything I like, the reason why I put an underscore is because when you name functions, data types, are really anything else in C it is illegal to have spaces between words, so replace the space with an underscore and you'll be fine. (int n) is telling the compiler what will be going into the function in this case n and n will be an integer hence int. Whenever you use a function your first have to prototype it. The prototype must go in between the pre-processor directives and int main(). Prototyping is something that is required in C programming, this is basically telling the compiler hey this is a function that I will be using so heads up. The easy part is that prototyping a function is literally typing in the same code I did above and adding a semicolon so that it would like this. Outside of your main program is where you will actually define the function, this is where you write the code of what the function is to do.
int my_function(int n);

So lets take a look at a program that uses a function to find the greater of two numbers a and b.
#include <stdio.h> #include <stdlib.h> int my_function(int a, int b); /*This is the prototype, notice how it's above main. This function takes in two arguments int a and int b*/ int main() { int a,b; printf("Please enter a number"); scanf("%i",&a); printf("Please enter another number"); scanf("%i",&b);

printf("The greater number is %i",my_function(a,b) ); /*This is how you call the function, its name and what variables you are sending it*/

system("pause"); return 0; } /*This is the part where we actually define the function, that is, write what the function is to do, also notice how we define the function completely out of main, this is how it will always be done*/ int my_function(int a, int b) { if (a>b) { return a; /*If a is greater than b we want the function to return just a*/ } if (b>a) { return b; /*If b is greater than a than we want the function to return just b*/ } }

You may already be asking yourself, couldn't we of just done this simple procedure in the main program, well yes! In order to keep complexity at a minimum this is a good program to demonstrate. However, in more complex programs functions are very useful and necessary. NOTE! Notice how we scanned in a and b and in our function our arguments were also a and b, it isn't required that the variable be the same, I could have just as easily declared x any y in my main program and sent those variables to my_function. It is required however, for your prototype and your defining of a function to be identical (aside from the prototype having a semicolon after it and the defining not). This can be a little confusing at first but practice makes perfect! Lets check out another program.
#include <stdio.h> #include <stdlib.h> double add(double a, double b); /*Prototype, this functions name is add and will accept to double parameters a & b and then return a double*/

int main() { double x,y; printf("Enter a value\n"); scanf("%lf",&x); printf("Enter another value to be added to the other value\n"); scanf("%lf",&y); printf("The sum of the two numbers is %.2f\n",add(x,y) );

system ("pause"); return 0; } double add(double a, double b) /*Defining the function*/ { double sum; /* Declaring a local variable called sum*/ sum=a+b; return sum; }

This program has a function that takes in two values, adds them, and then returns their sum. Notice how in the function there is two double values a and b but in the main program x and y is being sent, this is okay because the variables do not have to match. This is because x and y's values are being sent to a and b, as long as they are of the same data type (in this case double) you will be fine. Also notice how I declared a variable inside a function, whenever this is done the variable is local and is not used in the main program. Sum is just holding the sum of a and b and that is why the value of sum is what gets returned to the main program. The thing with functions is that when you pass a variable to them it is actually making a copy of that variable. It is this copy that it uses withing the function, this is a process called pass by value, this procedure is safe because it doesn't allow a variable to be altered in the function, the con however, is sometimes you want to alter a variable within a function. How do you get around this? Instead of passing a copy of the variable we pass its address, this way we are allowed to change a variables value. The next lesson will go over pointers, a handy tool that holds variables addresses.

_______________________________////////*****\\\\\\\----------------------------------------------

C Pointers
Pointers have commonly been given a bad reputation, this is because it's hard to see what pointers are for at first. Unfortunately, when you don't understand why something is used the less motivated you are to learn them. That being said, they are actually very useful tools so if you stick around you'll be happy you did. Here is the syntax for a pointer.
int *p;

This is how you declare a pointer, notice how it isn't all that different from declaring just a normal variable only you must put and asterisk in front of the variable. We have just declared p to be a pointer and p must point to an integer hence the int before *p. So how do we get p to point to something? Easy we give it an address.
p=&x;

P now points to the address of x. This is exactly what pointers do best, they hold the addresses of other variables. So whatever you do with *p, x will do the same. For example lets initialize *p to a value.
*p=5;

Can you guess what x is? Yes! 5. Because *p now points to x we can manipulate x just by manipulating *p. Lets see a basic program using a pointer.
#include <stdio.h> #include <stdlib.h> int main() { int x; int *p /*Declaring a pointer called p*/ p=&x; /*p now points to x*/ *p=6; /*Initialize the pointer to the value of 6; printf("%i",x); /*print out the value of x*/ system ("pause"); return 0; }

This program will print out whatever you intialize to *p. So you may already be asking yourself, instead of manipulating *p, couldn't we have just changed x directly. Yes, and this is where it can be confusing at first, but this example program doesn't show what pointers are necessarily for, this program is to show you how pointers work. The main reason for pointers is dereferencing data, instead of changing a variables value you change its address, why? In c programming when it comes to functions you cannot return a variable whose value has changed from within the function, but you can change it's address! First let us take a look at a function

that does NOT use pointers and attempts to change a value of a variable from within the function.
#include <stdio.h> #include <stdlib.h> int add_5(int n); /*Remember you must it*/ int main() { int x; scanf("%i",&x); /*scan in a value add_5(x); /*call the function printf("%i\n",x); /*prints out the system("pause"); return 0; } int add_5(int n) /*n now holds the value of x*/ { n=n+5; /*n equals what it was plus 5*/ return n; /*return n back to x/* } prototype the function before you use

for x*/ and send it the value of x*/ value of x*/

What this program does is simple, scan in a value of x, send it to a function that takes that value adds five and returns it. However, if you compiled and ran this program you would notice all it does is print out what you already entered, for example, if you entered 5 it would return 5 when you should be expecing 10 right? This is precisely what pointers are for, we cannot change the value of x, so we change it's address by using pointers. Now we will look at another program that is identical to the last only it is uses pointers.
#include <stdio.h> #include <stdlib.h> int add_5(int *p); /*prototype your function, this time we are using a pointer called *p */ int main() { int x; int *p; /*you must declare your pointer, the pointer is called p and it is going to point to an integer*/ scanf("%i",&x); p=&x; /*p now points to x*/ add_5(&x); /*careful on this one! Call the function add_5 and send it the address of x*/ printf("%i\n",x); system("pause"); return 0; } int add_5(int *p) /*define the function*/ {

*p=*p+5; /*pointer p equals what it was plus 5*/ return *p; /*return the pointer p*/ }

When you run this program you will see it works just how we wanted it to. The program takes in a value and returns the value plus 5. This is all thanks to pointers! Pointers are also very useful when using arrays. The next section will go over arrays but not how they are used with pointers, these lessons are intended for beginners and designed for someone new to programming to simply get a feel of what it is all about.

______________---_____---_____----_____----____----____________________

C Arrays
Arrays are convenient tools at your disposal when you want to store multiple values of a certain data type. When arrays are used inside of loops they become even more useful with storing certain data. Think of a variable as a small box, now think of an array as a single big box that can hold a whole bunch of little boxes (variables). Instead of having to search for little boxes you can put them all in one bigger box, label it, and have it at your quick disposal. For instance, up until now if you wanted to store multiple values for integer types you would probably do so like this.
int x=10; int y=23; int z=38;

It would be much more convenient if we could store these different values into one variable and call upon them as we please. Fortunately, this is possible through arrays, here is how you declare one.
int my_array[3];

This is how you declare an array. As always, int means that this array will store integer data types, my_array is simply the name of this array and the [3] means that it will hold three values. Once you have declared your array you're going to want to assign each integer a value, this is how you do so.
my_array={10,23,38};

Remember that this array holds three values, 10,23,and 38 are the values it will store, put these values in curly braces not the brackets,the brackets are used when you declare how many values are in the array in this case 3. You could also initialize an array individually like this.
my_array[0]=10; my_array[1]=23; my_array[2]=38;

I find the first way to more convenient however this way may be more clear, I will explain why the index number starts at [0] in a moment. Now that we have these integers stored in my_array lets print them out.
printf("%i",my_array[0] );

This is where it can get a little confusing, but just in the beginning so bare with me. Where did the [0] come from? The [0] will print out 10, this is because 10 is the first value in my_array. If we were to use my_array[1] it would've printed out to the screen 23 and if we used my_array[2] it would've printed out to the screen 38. Yes, it would make more sense for [1] to be 10, [2] to be 23, and [3] to be 38 but easy isn't always the most efficient. In c programming arrays are used from 0 to N-1, for instance with an array of 5 values its max index number would be [4]. Some languages do it the way that makes more sense but once the code is being compiled the array has

to be changed into the way that the c language initially uses them. This is because at the machine level there is just a bunch of zeros and ones. Having an array begin at [0] saves processing time and is therefore more efficient compared to if it began at [1]. Now lets take a look at a full working program that uses arrays.
#inlcude <stdio.h> #include <stdlib.h> int main() { int k; int my_array[5]; /*declares an array that will hold 5 integers*/ my_array={10,20,30,40,50}; /*these are the values of the 5 integers*/ for(k=0; k<5; k++) { printf("%i\n",my_array[k] ); /*when k is 0 my_array will print out 10 and so on all the way to k being 4*/ } system ("pause"); return 0; }

This program uses a for loop that executes 5 times each loop k is incremented by 1. In the second loop k is now at 1, therefore 1 is put into my_array[k]. my_array[1] will print out 20, after the loop executes k will be incremented by one making it 2, 2 will go into the place of k, my_array[2] will print out 30 and so on. If you are still a little confused it helps to code it and see how the program works yourself, doing this helps you get a better grasp on arrays and programming in general.

Arrays in Functions
Arrays can be manipulated through functions, unlike variable arrays work differently in functions. When a variable is used in a functions a copy of that variable is made and sent to the function, this saves the user from accidentally ever changing a variable within a function and losing those values permanently. Arrays work differently, instead of a copy being made the actual address is sent to the function (it would take a lot of memory to send copies), this being said, be sure to always be mindful of data in arrays when using functions, precious information could be lost. Aside from a few alterations, programming with arrays in functions isn't too different. Here is how a prototype of a function called array with one array parameter.
int array(int x [ ] );

This function will take in an array with integers and return a single integer, this would be ideal if we wanted the function to take all the values in the x array, add them up and return a single sum. If instead we wanted the whole array returned we would use void instead of int like this.
void array(int x[ ] );

void is used whenever we want more than a single value returned from a function, below is perfect example of a program that takes in ten values using an array, adds two to each of those values and returns the altered array back to the main program.
#include <stdio.h> #include <stdlib.h> void array_function(int x[ ] ); int main() { int k; int y[10]; /*declares an array named y that will 10 integer values for(k=0; k<=9; k++) scanf("%i",&y[k]); /*scans in a value 10 times*/ } array_function(y); /*calls the functions and sends it the values stored in array y */ for(k=0; k<=9; k++) { printf("\n%i",y[k]);/*after the function call, this loop prints out the new values*/ } return 0; } void array_function(int x[]) /*defining the function */ { int i; for(i=0; i<=9; i++) /*a loop that executes 10 times*/ { x[i]=x[i]+2; /*x[i] equals what it was plus 2*/ } }

_______________________________END_________________________________________

C Datafiles
Wouldn't it be nice to have a particular type of data and be able to calculate the numbers anytime you like? If you wanted the mean, average,standard deviation or anything else, simply write a program that pulls data from a text file on your own computer. This is possible through reading and writing data files with a program.

NOTE!
Your data file must be written as a text file using something like notepad or wordpad, if you were to use Microsoft Word or something similar it wouldn't work right.This is because word has data invisible to the naked eye that would interfere with a program. First let me show you an example of a data file, imagine that the first column is time in seconds and the other column is feet, lets write a program that can take input in for a given amount for time and give us the corresponding length. For example, if we put 4 in for time we would expect our program to print out 33, you can copy and paste this if you wish. 1 13 2 18 3 29 4 33 5 47 The first thing you must do when programming with a data file is name it, here is how. FILE *myfile; This name does not have to much the file name that is stored on your computer, FILE must be capitalized, notice the asterisk? myfile is a pointer, this means we must give it an adress. myfile=fopen("C:\\Program Files\\sample.txt","r"); I received the location of my file by right clicking the icon,scrolling down to properties and copying and pasting the location. Notice that when you do this there is only one slash not two how there is above, you must include another \ wherever there is one. Also, include two more slashes before you type in the name of your file, what you type in has to be the same name of your file stored in your computer. For instance my document was named sample, you must then add the .txt since it is text document. The "r" means that it is a read file, your program will read data from the file. If it were a "w" it would be a write file, your program will then write to the file. Now that we have opened the file, the safe thing to do is to check whether or not the file was opened successfully, this is done with a condition. if(myfile==NULL) printf("Error in opening file"); This is very useful if your program is giving trouble. Now that the the file is opened we want to scan in the data from the file to the program.

fscanf(myfile,"%i %i",&time,&feet); Notice how similar this is to a normal scanf, the extra f is for file. Since a data file is read just as you read from left to right, we must scan it in that way. We know that both time and feet are integers so %i is appropriate (assuming we have declared them as integers). WAIT! This will scan in the very first row of data the 1 for time and the 13 for feet right, but what about the rest of the data? Simple, all we have to do is tell the program that we are expecting two values, time and feet every time we scan the file, so once we scan the file and two values aren't scanned we know that this must be the end of the data file. We accomplish this with a while loop. while(fscanf(myfile,"%i %i",&time,&feet)==2) Keep scanning while there are two values if not, end of file. The last special thing we must do is close the file, this is just safe practice.
fclose(myfile);

There you have it, would you like to see a sample program? #include <stdio.h> #include <stdlib.h"> int main() { int time,feet; FILE *myfile; /*declare myfile a pointer to a file*/ myfile=fopen("C:\\Program Files\\sample.txt","r"); /*myfile points to the address of your text document*/ if(myfile==NULL) /*if your file didn't open print an error message*/ printf("Error in opening file"); else{ /*if it did open do this stuff*/ while(fscanf(myfile,"%i %i",&time,&feet)==2) /*while reading in two values every scan keep scanning*/ { printf("%i %i\n",time,feet); /*print out the values every scan*/ } } /*closes the else statement*/ fclose(myfile); /*close myfile*/ system("pause"); return 0; } This program scans and prints out the data in the text document you wrote with either notepad or wordpad. ****************************************************************************** **********************************END***************************************

Potrebbero piacerti anche