30 October 2013

Arrays and Self-Pointers

Let's jump a little bit further to "Arrays and Self-Pointers".
I apologize to go directly to this part, but I do have to explain this now. I will go back to the basics later on.

First of all, let's define the meaning of an Array. An array is a group of contiguous memory location that has a predefined size as well as one data type for all its elements.

Before I can explain the terms contiguous, predefined size, and one data type, I will first show you an example of array declaration :

  data_type array_name[size] = {element-1, element-2, element-2, ... , element-size};
Just like variables, you need to initialize the elements in an Array before using it to prevent runtime errors. It is done by assigning values to each of the elements in the array using the equal sign (=) then followed by an open parenthesis and the value of element-1, element-2, and so on, then finally closing it up with a closing parenthesis.

 Now, I am going to explain about the terms.
  • Contiguous
           It means every element in an Array is located next to one another in the memory depending on  their index. Why is this so important?

           With this feature of array, it is possible to do sorting, searching, and many more since you can easily loop through every element in an Array due to its elements contiguous memory location. This will be shown in an example later in the post.

  • A Predefined Size
           Since an Array's memory locations for its elements need to be contiguous, it needs a proper declaration for size, so that it can allocate the space in the memory for storing the value of the elements it has.Once the size is declared, an array cannot be resized during runtime.

  •  One Data Type
            An Array can only store elements of one uniform data type.
            Example : an int array can only store integer values in it.
            Why? If you refer to the previous post about variables, you can see that every data type has different sizes, so, if you store a double value into an integer array, you will absolutely get the wrong value when you use the value again, which is why you can only store values with the same data type.

Viewing The Value of An Array Element

To look at the value of an array element, you can simply use printf or any other output functions in C.

Note : An array index starts from 0, so an array[0] will have indexes of 0-9 only.

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


int main(){
//Declaring an Integer Array with the size of 4
 int array[4] = {1, 3, 5, 7};
//Prints the value in index 0 of array[4]
 printf("array[0] = %d\n", array[0]);  
//Prints the value in index 1 of array[4]
 printf("array[1] = %d\n", array[1]);  
//Prints the value in index 2 of array[4]
 printf("array[2] = %d\n", array[2]);  
//Prints the value in index 3 of array[4]
 printf("array[3] = %d\n", array[3]);
/*Pausing the screen to see results,
**because dev-cpp does not freeze at the end of program
**/ 
 system("Pause");
//returns 0 to indicate successful run
 return 0;  
}
 To see how it works, just type the code into your Dev-Cpp (or other IDEs) and run.

Assigning Values to Array Elements

To assign values to an array element, you simply use this syntax:
array_name[index] = value;
 Example:

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


    int main(){
    //Declaring an Integer Array with the size of 4
     int array[4] = {1, 3, 5, 7};
    //Prints the value in index 0 of array[4] before value changes
     printf("array[0] = %d\n", array[0]);
    //Asigns value 9 to array[0]
     array[0] = 9;
    //Prints the value in index 0 of array[4] after value changes
     printf("array[0] = %d\n", array[0]); 
    system("Pause");
    return 0;
    }


Self-Pointers

Now, we come to an interesting part of the Array data structure.
Please take note that : An array's name is  the address of its first element in memory.

Let's say you have an array of size 10.
Assuming that the address of its first element is 123, the address of its second element would be 124, and the address of its third element would be 125, and so on. How is that possible? Scroll to the Contiguous section.

Now how can we make use of that?
First, I would like to introduce Pointer to you.
A pointer is a variable that stores the memory location of another storage types(variables, arrays, etc.).
Okay, so it stores memory locations, now what?
If you assign an array's name to it, what happens?  It stores the location of the first element of the array in the memory. Then what can you do with that?
You can easily do pass-by-reference to functions, you can do self-pointing, you can also view/modify the value of an array element without actually having to access the array itself (indirection), and many more.

As an example, I will show you how to use pointers to self-point using an array.

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


int main(){
//Declaring an Integer Array with the size of 4
 int array[4] = {1, 3, 5, 7};

 printf("Viewing array elements through indexes :\n");
//Prints the value in index 0 of array[4]
 printf("array[0] = %d\n", array[0]);  
//Prints the value in index 1 of array[4]
 printf("array[1] = %d\n", array[1]);  
//Prints the value in index 2 of array[4]
 printf("array[2] = %d\n", array[2]);  
//Prints the value in index 3 of array[4]
 printf("array[3] = %d\n", array[3]);
 printf("\nViewing array elements through self-pointers :\n");
 //Prints the value in location 'array'
 printf("array[0] = %d\n", *array);  
//Prints the value in location 'array+1'
 printf("array[1] = %d\n", *(array+1));  
//Prints the value in location 'array+2'
 printf("array[2] = %d\n", *(array+2));  
//Prints the value in location 'array+3'
 printf("array[3] = %d\n", *(array+3));

 system("Pause");
 return 0;  
}


You can also assign values to an array element using a self-pointer.

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


    int main(){
    //Declaring an Integer Array with the size of 4
     int array[4] = {1, 3, 5, 7};
    //Prints the value in index 1 of array[4] before value changes
     printf("array[1] = %d\n", array[1]);
    //Asigns value 9 to array[1] using a pointer
     *(array+1) = 9;
    //Prints the value in index 1 of array[4] after value changes
     printf("array[1] = %d\n", array[1]); 
    system("Pause");
    return 0;
    }


That was just a preview on Pointers. More on next posts.
Hope it inspires you.



Happy Coding,
Cyber Frost

27 October 2013

Variables in C

Just like any other programming languages, C also has variables.
If you do not know already, a variable is a storage location for several types of values.
There are 4 basic types of variable type specifiers in C, according to Wikipedia :

-char
-int 
-float 
-double

 
which can be combined with optional specifiers :

-signed 
-unsigned 
-short 
-long


In total, there are 28 basic data types in C. Here is the complete list along with the description: http://en.wikipedia.org/wiki/C_data_types

The syntax to declare a variable in C is simple, which is :
data_type var_name = initial_value;
Let's see how we use it in a C source code:

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

int main(){
//declaring the variables
int a = 5;
int b = 2;
int c = a + b;
//printing the value of c, which is a+b, or 5+2
printf("%d",c);
//printing a new line
printf("\n");
//pausing the program to see the result
system("Pause");
return 0;
}
If you can see, I wrote several lines of words using a "//" sign in front. They are called comments. Comments will not be run by the compiler, they are only used to aid programmers to understand the source code. More about comments in the next post.

From the code you can see that I declared an Integer a with the initial value of 5 and Integer b with the initial value of 2. I then declared another Integer c with the value of a + b. Next, I print out the result, which is the value of c using printf.
You can also use other data types for different operations. Let's do division with integer and float data types for example. Here is the code :
#include <stdio.h>
#include <stdlib.h>

int main(){
//declaring the variables
float a=5;
int b=2;
float c=a/b;
//printing the value of c, which is a/b, or 5/2
printf("%f",c);
//printing a new line
printf("\n");
//pausing the program to see the result
system("Pause");
return 0;
}
The code is pretty much the same, with small modifications here and there.
If you notice, we cannot use integers as the dividend here. Why?
An Integer will always be a non-decimal number, which will give you a wrong result of the division if you declare a or c, or both, as an Integer. Ex : 5/2 = 2.

There you go. Now you can apply variables in your codes. Congratulations !
 


Happy Coding,
Cyber Frost

Basic Structure of C Programs

Every programming language has its basic structure, that is, how and where the lines of code are written.

In C, it looks like this :
#include <stdio.h>

int main(){
    //statement1;
    //statement2;
    //..........;

return 0;
}
Let's start from the top.

The #include statement is used for including a header file into your program. In this case, stdio.h.
It must precede any other lines of code in your source file.
The int is a return type specifier for the function main(). Every C program must have a main() function in order to run. Even though your program has a thousand lines of code, it will start by executing the main() function.

More about return type of main():
The main() function returns 0. which is an int as an indicator to the compiler that the program was well-executed (without error).

Then, there are these symbols, the {parentheses}, to indicate the start and the end of the main() function. Every line of code, or statement, within the parentheses must be followed by a semicolon (;).

Finally, there is the return statement, which pretty much describes its function already : to return a value from the function it represents. In this case, it is the main() function.

The End. By now you should have the basic knowledge to start writing codes in C.



Happy Coding,
Cyber Frost

Coding in C using Dev-Cpp IDE

Greetings, fellow coders.

Today, I am going to show you an open-source application which enables easy coding and compiling of C programs. It is named Dev-Cpp or Dev-C++, which can be used as an IDE(Integrated Development Environment) to code and to compile C++ as well as C programs.

You can get a free copy of it here :  http://www.bloodshed.net/dev/devcpp.html

After you downloaded and installed Dev-Cpp on your computer, run the devcpp.exe file.

After the splash screen you will see :


Simply close the Tip of the Day window and we shall continue.

At the top left of Dev-Cpp, you will see the File menu, click on it to start a new Project or Source.

Let's try to create a C source file.
Click on File>New>Source File. A new tab will open up, like this :



Now type in this code to the code editor:
#include <stdio.h>
#include <stdlib.h>

int main(){
 printf("Hello World\n");
 system("Pause"); 
 return 0;  
}
 Done? Now click the Execute menu and choose Compile & Run or simply press F9.
 It will then ask you to save the source file first. Just save it wherever you desire, but make sure it is in the C source files (*.c) format.
 After saving, a window will show up, looking like this :



Congratulations, you have successfully created a C program using Dev-Cpp !

On the next few posts, I will be giving tutorials on creating C programs with this user-friendly IDE.




Happy Coding,
Cyber Frost

Search