When programming, it is important to know which variables you can use where. I'll explain.
Let's say you declare a global integer x, and you define a function myFunct(). In the definition of myFunct(). You would obviously be able to use this integer x. But does it go the other way around? That is, can you use variable declared inside a function outside the function?
Simple answer. No.
When you call a function, the "flow" of your program halts so that it can go run your function and then return with the results. Let's say we have a function add2()
int add2(int x)
{
int y = 2;
return x+y;
}
Yes, I know there's no reason to declare this variable y, but it's for the sake of the example. In this case, The variable called y only "lives" until the end of the function. After that, this variable no longer exists, and hence it can no longer be referred to (Things like this can be overcome using the "static" keyword. I'll mention this sometime). In fact, this variable x no longer exists either. x is just a temporary holder for a value that is used while the function is running!
Functions are just one example of where knowledge of a scope could be useful. Let's say you were running a for loop.
int i;
for(i=0;i<5;i++)
{
//do stuff
}
Clearly, this is just an average for loop. Runs whatever code between its curly brackets 5 times. Now check this out:
for(int i=0;i<5;i++)
{
//do other stuff
}
Can you see the difference?
The difference is that in the first case, the variable i would be usable even after the for loop was executed. In the second case, i "dies" as soon as the loop terminates. Personally, I like to use the second method just because it allows me to use the same identifier for all my loops (assuming they're not nested) without fear of that identifier already being declared and used for another loop. I also just find it neater ;)
Sunday, 20 March 2011
Friday, 18 March 2011
Simple Functions
Functions are the basis for writing programs in C. They allow you to efficiently run repeated lines of code. For example, take a look at this mathematical function:
f(x) = x2
This function takes any real number x and squares it. Another way of writing this function could be:
f(x) = x*x
In C. Functions have 3 "Parts":
1) The function prototype which tells the program what to expect when the function is defined.
2) The function definition which tells the program how to execute the function.
3) The function call, which actually runs the function.
For this example, let's look at this square example. To declare a function, you must specify its return type (more on this is a sec) and then give the function an identifier and specify its parameter type. The parameters are the values that get passed into and used by the function (in f(x), our parameter is x). Here's a function prototype for our square function.
int square(int);
Later in your program, usually after your main method (unless you decide to declare it before, in which case a function prototype is not necessary), you will include your function definition. Here's the definition for square.
int square(int x)
{
return x*x;
}
A really simple function. The program will take whatever value gets passed into the function. That value is now represented by x. The function now calculates the square of x and returns the value back to wherever the function was called. Here's an example showing how to call this function
#include<stdio.h>
int square(int);
int main()
{
y=2;
printf("The square of %d is % d.\n",y,square(y));
return 0;
}
int square(int x)
{
return x*x;
}
Compile this and you'll see that the output of the program is:
The square of 2 is 4.
Notice how to call the function, you simply write the function name and then the values you want to pass into the function (These are called the arguments).
This function takes any real number x and squares it. Another way of writing this function could be:
f(x) = x*x
In C. Functions have 3 "Parts":
1) The function prototype which tells the program what to expect when the function is defined.
2) The function definition which tells the program how to execute the function.
3) The function call, which actually runs the function.
For this example, let's look at this square example. To declare a function, you must specify its return type (more on this is a sec) and then give the function an identifier and specify its parameter type. The parameters are the values that get passed into and used by the function (in f(x), our parameter is x). Here's a function prototype for our square function.
int square(int);
Later in your program, usually after your main method (unless you decide to declare it before, in which case a function prototype is not necessary), you will include your function definition. Here's the definition for square.
int square(int x)
{
return x*x;
}
A really simple function. The program will take whatever value gets passed into the function. That value is now represented by x. The function now calculates the square of x and returns the value back to wherever the function was called. Here's an example showing how to call this function
#include<stdio.h>
int square(int);
int main()
{
y=2;
printf("The square of %d is % d.\n",y,square(y));
return 0;
}
int square(int x)
{
return x*x;
}
Compile this and you'll see that the output of the program is:
The square of 2 is 4.
Notice how to call the function, you simply write the function name and then the values you want to pass into the function (These are called the arguments).
Wednesday, 16 March 2011
Declaring and initialising variables
Today, I'll show you how to declare and initialize variables and talk about the possible types.
C has a few "core" data types called primitives these data types typically hold some sort of numerical value. The following are primitives:
int (integers)
long (integers)
float (real numbers)
double (real numbers)
char (characters)
The most used primitives are int, float, and char. Long and double are simply ints and floats respectively which allow a wider range of values.
Declaring a variable is easy. You first type the type of variable you want to declare, and then you give it an identifier (a name) which must start with a letter and may contain numbers and underscore characters as well. For example:
would declare an integer with the name x. You can now assign a value to x using the assignment operator =.
This would store a value of 5 in x. It is also possible to combine declaration and assignment in one line.
is also acceptable. floats are declared in the same way.
however, attempting something like:
would cause an error, because 3.14 is not an integer.
Declaring characters is done in the same way, however, assignment is slightly different.
This would declare a character and hold the character 'f' in it.
Every character has its own unique code to identify it. Given the 256 standard characters, these codes are called ASCII codes and each ASCII character has its own. In C, when you store a character in a variable, you are actually storing the value of its ASCII code. When you want to specify that you're talking about a character, you must put it between apostrophes.
Next time, I'll talk about modifying the contents of variables and displaying their contents using printf();
C has a few "core" data types called primitives these data types typically hold some sort of numerical value. The following are primitives:
int (integers)
long (integers)
float (real numbers)
double (real numbers)
char (characters)
The most used primitives are int, float, and char. Long and double are simply ints and floats respectively which allow a wider range of values.
Declaring a variable is easy. You first type the type of variable you want to declare, and then you give it an identifier (a name) which must start with a letter and may contain numbers and underscore characters as well. For example:
int x;
would declare an integer with the name x. You can now assign a value to x using the assignment operator =.
x=5;
This would store a value of 5 in x. It is also possible to combine declaration and assignment in one line.
int x=5;
is also acceptable. floats are declared in the same way.
float y=2.7;
however, attempting something like:
int z=3.14;
would cause an error, because 3.14 is not an integer.
Declaring characters is done in the same way, however, assignment is slightly different.
char c='f';
This would declare a character and hold the character 'f' in it.
Every character has its own unique code to identify it. Given the 256 standard characters, these codes are called ASCII codes and each ASCII character has its own. In C, when you store a character in a variable, you are actually storing the value of its ASCII code. When you want to specify that you're talking about a character, you must put it between apostrophes.
Next time, I'll talk about modifying the contents of variables and displaying their contents using printf();
Tuesday, 15 March 2011
Back to basics
So I've been getting some comments and messages about my posts being too advanced, So I've decided that it would probably make more sense to start C from the beginning. In this post, I'll show you how to write a basic "Hello World!" program and explain the ins and outs of it. Some things will just be touched on right now and more fully explained in later posts.
#include<stdio.h>
int main()
{
printf("Hello World!");
return 0;
}
To fully understand how the program works, I'll explain its components.
#include<stdio.h>
#include is a macro. This particular macro goes and finds a file on your computer, in this case stdio.h. This file is what we call a header file. Basically, this file contains a bunch of function definitions (again, more on this later). The #include macro tells the program to go look in the folder on your computer containing your standard C library header files and to find stdio.h. When you hit the "build" button, the compiler will take your source code and compile it into machine code, but even before that, something called the preprocessor (we'll mention this again much later) will physically copy all the text from stdio.h into your program. Now when your program gets compiled, the compiler sees all this code in your program, so it actually becomes a part of your program.
int main()
{
}
Functions are very important in any programming language. Every program in C must have a main function. Everything contained within the curly brackets will be code executed during runtime.
printf("Hello World");
This is a call the function which prints to the screen. This printf function is defined within the stdio.h file. Having included that file, we are able to call this function. Here, we can see that the text we are printing to the screen is "Hello World".
return 0;
To indicate to the operating system that the program has terminated successfully (ie. No runtime errors occurred/The program did not crash/etc) we return 0 at the end of out main. This signifies the end of our program.
I hope this has been useful to those not yet fully comfortable with C.
#include<stdio.h>
int main()
{
printf("Hello World!");
return 0;
}
To fully understand how the program works, I'll explain its components.
#include<stdio.h>
#include is a macro. This particular macro goes and finds a file on your computer, in this case stdio.h. This file is what we call a header file. Basically, this file contains a bunch of function definitions (again, more on this later). The #include macro tells the program to go look in the folder on your computer containing your standard C library header files and to find stdio.h. When you hit the "build" button, the compiler will take your source code and compile it into machine code, but even before that, something called the preprocessor (we'll mention this again much later) will physically copy all the text from stdio.h into your program. Now when your program gets compiled, the compiler sees all this code in your program, so it actually becomes a part of your program.
int main()
{
}
Functions are very important in any programming language. Every program in C must have a main function. Everything contained within the curly brackets will be code executed during runtime.
printf("Hello World");
This is a call the function which prints to the screen. This printf function is defined within the stdio.h file. Having included that file, we are able to call this function. Here, we can see that the text we are printing to the screen is "Hello World".
return 0;
To indicate to the operating system that the program has terminated successfully (ie. No runtime errors occurred/The program did not crash/etc) we return 0 at the end of out main. This signifies the end of our program.
I hope this has been useful to those not yet fully comfortable with C.
Sunday, 13 March 2011
Recursion
Probably one of the more controversial topics in terms of usefulness. Today, I'll show you how to write some simple recursive functions and in an upcoming post, I'll show you guys how it can be useful outside of mathematical applications.
So first off, what exactly is a recursive function. A recursive function is a function that keeps calling itself, until it reaches a base case. Once the base case is reached, then the function calls will return all the values to the previous function calls until the original call to the function returns its value.
This sounds like a lot, but I'll explain it using examples. First, let's look at the factorial function.
For example, we know that:
4! = 4*3*2*1 = 24
5! = 5*4*3*2*1 = 120
etc.
Written as a recurrence relation, the factorial function looks like:
an = n*an-1
a1 = 1
So let's say we wanted to find the 3rd element in this relation, a3. It will be equal to 3 times a2
a3 = 3*a2
and a2 is equal to 2 times a1
a2 = 2*a1
and a1 is 1
a1 = 1 (This is the base case)
So like this we can write
a2 = 2*1
a3 = 3*(2*1) = 6
So let's say we wanted to find the 3rd element in this relation, a3. It will be equal to 3 times a2
a3 = 3*a2
and a2 is equal to 2 times a1
a2 = 2*a1
and a1 is 1
a1 = 1 (This is the base case)
So like this we can write
a2 = 2*1
a3 = 3*(2*1) = 6
And we have our answer!
This is how a recursive function works. See how the function would keep "calling" itself until it reached a base case that was not a recursive call?
Now let's see how we can apply this as a function in C.
int factorial(int n)
{
if(n==1 || n==0)
return 1;
else
return n*factorial(n-1);
}
Notice how each time a recursive call is made, we first check to see if n is our base case, and if not, we do recursive calls. Of course, this code is buggy in that if we passed a negative number into the function, it would loop forever, but simple modifications can fix that.
So now that you've seen how it's done, you may be wondering how it works.
Every time a recursive call is made, the scope of the previous call is held in memory and "awaits" an answer from the call that it made. With the example earlier where we calculated 3!, the first call, makes a another call which then makes another call. The 3rd call will return the base case which then gets multiplied by 2 and returned to the first call. The original call then multiplies 2 by 3 and then returns the value to wherever the original call was made.
Later, I'll show you how to apply recursive functions to practical situations where math is not directly involved.
This is how a recursive function works. See how the function would keep "calling" itself until it reached a base case that was not a recursive call?
Now let's see how we can apply this as a function in C.
int factorial(int n)
{
if(n==1 || n==0)
return 1;
else
return n*factorial(n-1);
}
Notice how each time a recursive call is made, we first check to see if n is our base case, and if not, we do recursive calls. Of course, this code is buggy in that if we passed a negative number into the function, it would loop forever, but simple modifications can fix that.
So now that you've seen how it's done, you may be wondering how it works.
Every time a recursive call is made, the scope of the previous call is held in memory and "awaits" an answer from the call that it made. With the example earlier where we calculated 3!, the first call, makes a another call which then makes another call. The 3rd call will return the base case which then gets multiplied by 2 and returned to the first call. The original call then multiplies 2 by 3 and then returns the value to wherever the original call was made.
Later, I'll show you how to apply recursive functions to practical situations where math is not directly involved.
Friday, 11 March 2011
Calculus
Being a computer science major, I need to take lots of different kinds of math courses. One of these classes is calculus. Now I'd like to say that I like calculus as much as I like discrete mathematics or linear algebra, but that's not the case. Gone are the days when we would take derivatives of polynomials and that was it. Now it's like "Oh what's that, you've just finally understood u-substitution? Great because now we're going to start integration by parts. Also, remember the Cartesian coordinate system? Yeah so we're going to plot things based on r and theta now, not x and y." FML. I love math, I just don't like this particular area of it. Saying this, I do have to ensure everyone that I do understand its importance and usefulness. Calculus is a very useful tool for optimization problems, especially for civil and mechanical engineers. I'm just not all that into it.
More discrete math please!
More discrete math please!
Thursday, 10 March 2011
Variable length argument lists
I wrote my midterm for computer programming today and a good portion of it focused on variable length argument lists. What is that you may ask? Well take a look at a random function:
int square(int x)
{
return x*x;
}
This function takes one argument - an integer which is multiplied by itself to give its square.
Now let's look at C's function printf() which is used to print text to the command prompt. We could simply tell it to print a string:
printf("Hello");
or we could use to print a value stored in a variable:
int x=6;
printf("The value of x is %d",x);
we can do as many variables as we want!
int x=3;
float y=6.3;
printf("%d %f",x,y);
Now if you're like me when I started out with C, you're probably thinking "How does the function know when to stop printing, and what types of variables to expect?" Well we're not going to write out the implementation of printf() as that takes numerous cross-referencing libraries, but we are going to do a function with a variable length argument list that finds the average of a unspecified number of numbers.
The required functions are stored in stdarg.h so we first need to include that:
#include <stdarg.h>
Now that we have the proper tools, let's look at how a variable argument list is created. There are 4 main "tools" we will be using:
1) va_list identifier
This declares a variable of type va_list. This is sort of like a pointer to your arguments.
2) va_start(identifier, first argument)
This tells the list where we're starting. The obvious location is the first argument. Note that you must have at least one defined parameter when dealing with variable length argument lists (more on this later)
3) va_arg(indentifier, type)
This is what we will be using to acquire the values form our arguments. Note that the identifier used here is the same one used to declare our va_list
4) va_end(identifier)
This is just to clean up nicely. It tells our program "Ok, we're done with this list of arguments, let's clean up now"
So now that we've defined the necessary tools, let's get to the implementation of the function:
float average(int n,...)
{
float sum=0;
va_list arg;
va_start(arg,n);
for(int i=0;i<n;i++)
{
sum+=va_arg(arg,float);
}
va_end(arg);
return sum/n;
}
So let's go through it bit by bit:
When declaring a function with a variable length argument list, you MUST have at least one definitive argument. In this case, we are taking that argument to be the number of numbers we would like to average. As we all know, to average numbers, you take the sum of the numbers (float sum), and then divide it by the amount of numbers you have (int n).
So we start off by declaring our va_list and initializing the va_start(). Note that after suing va_start, the pointer now points at the 2nd argument (if available).
Next is our for loop which will loop n times to sum up all the integers. After doing that, we call va_end() to clean up. And then return sum/n, which will be our average!
A sample call of this function could be:
float x = average(3,6,4,5);
In which case, the value of x would be 5 since (4+5+6)/3 = (15/3) = 5
I hope this has been useful! I just thought I would share this piece of information with everyone!
Subscribe to:
Posts (Atom)