.

get our extension
Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, 24 September 2014

Learn C Programming Lesson 8 - Functions

BY Unknown IN , No comments


Learn C Programming Lesson 8 - Functions

Functions are sub-programs. You have already been using a function which is the main function.

You must always declare a function before the function that calls it. The main function will be calling our function so we will put ours above main.

First put its return value such as int or char. If you don't want a return value then use void. After that give it a unique name and put a set of brackets after that. You then put the set of curly brackets which will have the sub-program between them. We will call our function Hello because it will simply print the word Hello on the screen.
#include

void Hello()
{
   printf("Hello\n");
}

int main()
{
   Hello();
   return 0;
}
PARAMETERS:

Parameters are values that are given to a function so that it can perform calculations with them. The "Hello\n" which we used in the Hello function is a parameter which has been passed to the printf function.

You need to declare variables inside the parameter brackets to store the values of the parameters that are passed to the function. Here is an Add function which adds the 2 parameters together and then returns the result.
#include

int Add(int a,int b)
{
   return a + b;
}

int main()
{
   int answer;
   answer = Add(5,7);
   return 0;
}
You can pass the address of a variable to a function so that a copy isn't made. For this you need a pointer.
#include

int Add(int *a,int *b)
{
   return *a + *b;
}

int main()
{
   int answer;
   int num1 = 5;
   int num2 = 7;
   answer = Add(&num1,&num2);
   printf("%d\n",answer);
   return 0;
}
Global And Local Variables:

A local variable is one that is declared inside a function and can only be used by that function. If you declare a variable outside all functions then it is a global variable and can be used by all functions in a program.

#include

// Global variables
int a;
int b;

int Add()
{
   return a + b;
}

int main()
{
   int answer; // Local variable
   a = 5;
   b = 7;
   answer = Add();
   printf("%d\n",answer);
   return 0;
}
Command-Line Parameters:

Sometimes you also pass parameters from the command-line to your program. Here is an example:

$ myprogram -A

To be able to access the command line parameters you have to declare variables for them in the brackets of the main function. The first parameter is the number of arguments passed. The name of the program also counts as a parameter and is parameter 0. The second parameter is the arguments in a string array.

#include

int main(int argc,char *argv[])
{
   int i;
   printf("Amount: %d\n",argc);
   if (argc > 0)
   {
      printf("Parameters:\n");
      for (i = 0;i < argc;i++)
         printf("%s\n",argv[i]);
   }
   return 0;
}

PREVIOUS                                              NEXT 

Learn C Programming Lesson 7 String

BY Unknown IN , No comments


Learn C Programming Lesson 7 - Strings

A string is an array of characters. Strings must have a 0 or null character after the last character to show where the string ends. The null character is not included in the string.

There are 2 ways of using strings. The first is with a character array and the second is with a string pointer.

A character array is declared in the same way as a normal array.
char ca[10];
You must set the value of each individual element of the array to the character you want and you must make the last character a 0. Remember to use %s when printing the string.
char ca[10];
ca[0] = 'H';
ca[1] = 'e';
ca[2] = 'l';
ca[3] = 'l';
ca[4] = 'o';
ca[5] = 0;
printf("%s",ca);
String pointers are declared as a pointer to a char.
char *sp;
When you assign a value to the string pointer it will automatically put the 0 in for you unlike character arrays.
char *sp;
sp = "Hello";
printf("%s",sp);
You can read a string into only a character array using scanf and not a string pointer. If you want to read into a string pointer then you must make it point to a character array.
char ca[10],*sp;
scanf("%s",ca);
sp = ca;
scanf("%s",sp);
String Handling Functions:
The strings.h header file has some useful functions for working with strings. Here are some of the functions you will use most often:

strcpy(destination,source)
You can't just use string1 = string2 in C. You have to use the strcpy function to copy one string to another. strcpy copies the source string to the destination string.
s1 = "abc";
s2 = "xyz";
strcpy(s1,s2); // s1 = "xyz"
strcat(destination,source)
Joins the destination and source strings and puts the joined string into the destination string.
s1 = "abc";
s2 = "xyz";
strcat(s1,s2); // s1 = "abcxyz"
strcmp(first,second)
Compares the first and second strings. If the first string is greater than the second one then a number higher than 0 is returned. If the first string is less than the second then a number lower than 0 is returned. If the strings are equal then 0 is returned.
    s1 = "abc";
    s2 = "abc";
    i = strcmp(s1,s2); // i = 0
strlen(string)
Returns the amount of characters in a string.
s = "abcde";
i = strlen(s); // i = 5

PREVIOUS                                                                                   NEXT

Sunday, 14 September 2014

Learn C Programming Lesson 6 - Arrays

BY Unknown IN , No comments


Learn C Programming Tutorial Lesson 6 - Arrays

Up until now if you wanted to declare 5 variables you would have to do something like this:

int i1,i2,i3,i4,i5;

What if you wanted to declare 100 variables? That would take quite a long time. If you use an array on the other hand then you can declare as many variables as you want with only 1 variable name.

An array is declared in the same way as a normal variable except that you must put square brackets after the variable name. You must also put the amount of elements you want in the array in these sqaure brackets.

int a[5];

To access the value of an element of an array you must again use the square brackets but with the number of the element you want to access. When accessing an element of an array you must remember that they start from 0 and not 1. This means that an array which has 5 elements has an element range of 0 to 4.

int a[5];
a[0] = 12;
a[1] = 23;
a[2] = 34;
a[3] = 45;
a[4] = 56;
printf("%d",a[0]);

Using Arrays With Loops:

The most useful thing to do with an array is use it in a loop. This is because the element number follow a sequence just like a loop does.

When an array is declared the values are not set to 0 automatically. You will sometimes want to set the values of all elements to 0. This is called initializing the array. Here is an example of how to initialize an array of 10 elements using a for loop:

int a[10];
for (i = 0;i < 10;i++)
   a[i] = 0;

Multi-Dimensional Arrays:

The arrays we have been using so far are called 1-dimensional arrays because they only have what can be thought of a 1 column of elements. 2-dimensional arrays have rows and columns. Here is a picture which explains it better:






























You do get 3-dimensional arrays and more but they are not used as often. Here is an example of how you declare a 2-dimensional array and how to use it. This example uses 2 loops because it has to go through both rows and columns.

int a[3][3],i,j;
for (i = 0;i < 3;i++)
   for (j = 0;j < 3;j++)
      a[i][j] = 0; 

< PREVIOUS        START OVER        NEXT >


Sunday, 7 September 2014

Learn C Programming Lesson 5 - Pointers

BY Unknown IN , No comments


Learn C Programming Tutorial Lesson 5 - Pointers

What are pointers:

A pointer is a variable that holds a memory address. Because it holds a memory address it is said to be pointing to the value at that memory location. You can use a pointer in a certain way to get the value at the address to which it points.

Pointers can be either typed or untyped. A typed pointer points to a particular variable type such as an integer. An untyped pointer points to any data type.

To declare a pointer you must put a * in front of its name. Here is an examaple of how to declare a pointer to an integer and an untyped pointer:

int main()
{
   int *p;
   void *up;
   return 0;
}

You can put the address of an integer into a pointer to an integer by using the & operator to get the integer's address.

int main()
{
   int i;
   int *p;
   i = 5;
   p = &i;
   return 0;
}

You can access the value of the integer that is being pointed to by dereferencing the pointer. The * is used to dereference a pointer. Changing the value pointed to by the integer will change the value of the integer.

int main()
{
   int i,j;
   int *p;
   i = 5;
   p = &i;
   j = *p; //j = i
   *p = 7; //i = 7
   return 0;
}

Using pointers in the above way is just a long way of saying j = i. You will find out about much more useful ways to use pointers later on but for now it is only important that you have a basic idea of how they work.

NEXT LESSON NO #6

Report An Error Or Mistake !



Saturday, 6 September 2014

Learn C Programming Lesson 4 - Loops

BY Unknown IN , No comments


Learn C programming tutorial lesson 4 - Loops

What are loops:

Sometimes you will want to do something a lot of times. An example would be printing a character at the beginning of each line on the screen. To do this you would have to type out 24 printf commands because there are 25 rows on the screen and the 25th row will be left blank. We can use a loop to do this for us and only have to type 1 printf command. There are 3 basic types of loops which are the for loop, while loop and do while loop.

The for loop:

The for loop lets you loop from one number to another number and increases by a specified number each time. This loop is best suited for the above problem because we know exactly how many times we need to loop for. The for loop uses the following structure:

for (starting number;loop condition;increase variable)
   command;
With loops you also have to put commands between curly brackets if there is more than one of them. Here is the solution to the problem that we had with the 24 printf commands:

#include

int main()
{
   int i;
   for (i = 1;i <= 24;i++)
      printf("H\n");
   return 0;
}
A for loop is made up of 3 parts inside its brackets which are separated by semi-colons. The first part initializes the loop variable. The loop variable controls and counts the number of times a loop runs. In the example the loop variable is called i and is initialized to 1. The second part of the for loop is the condition a loop must meet to keep running. In the example the loop will run while i is less than or equal to 24 or in other words it will run 24 times. The third part is the loop variable incrementer. In the example i++ has been used which is the same as saying i = i + 1. This is called incrementing. Each time the loop runs i has 1 added to it. It is also possible to use i-- to subtract 1 from a variable in which case it's called decrementing.

The while loop

The while loop is different from the for loop because it is used when you don't know how many times you want the loop to run. You also have to always make sure you initialize the loop variable before you enter the loop. Another thing you have to do is increment the variable inside the loop. Here is an example of a while loop that runs the amount of times that the user enters:

#include

int main()
{
   int i,times;
   scanf("%d",&times);
   i = 0;
   while (i <= times)
   {
      i++;
      printf("%d\n",i);
   }
   return 0;
}
The do while loop

The do while loop is the same as the while loop except that it tests the condition at the bottom of the loop.

#include

int main()
{
   int i,times;
   scanf("%d",&times);
   i = 0;
   do
   {
      i++;
      printf("%d\n",i);
   }
   while (i <= times);
   return 0;
}
Break and continue

You can exit out of a loop at any time using the break statement. This is useful when you want a loop to stop running because a condition has been met other than the loop end condition.

#include

int main()
{
   int i;
   while (i < 10)
   {
      i++;
      if (i == 5)
         break;
   }
   return 0;
}
You can use continue to skip the rest of the current loop and start from the top again while incrementing the loop variable again. The following example will never print "Hello" because of the continue.

#include

int main()
{
   int i;
   while (i < 10)
   {
      i++;
      continue;
      printf("Hello\n");
   }
   return 0;
}

NEXT LESSON NO 5

Report An Error Or Mistake !













Learn C Programming Lesson 3 - Decisions

BY Unknown IN , No comments


Learn C Programming Tutorial Lesson 3 - Decisions

The If Statement :
So far we have only learnt how to make programs that do one thing after the other without being able to make decisions. The if statement can be used to test conditions so that we can alter the flow of a program. The following example has the basic structure of an if statement:

#include

int main()
{
   int mark;
   char pass;
   scanf("%d",&mark);
   if (mark > 40)
      pass = 'y';
   return 0;
}

In the above example the user enters the mark they got and then the if statement is used to test if the mark is greater than 40. Make sure you remember to always put the conditions of the if statement in brackets. If the mark is greater than 40 then it is a pass.

Now we must also test if the user has failed. We could do it by adding another if statement but there is a better way which is to use the else statement that goes with the if statement.

#include

int main()
{
   int mark;
   char pass;
   scanf("%d" ,&mark);
   if (mark > 40)
      pass = 'y';
   else
      pass = 'n';
   return 0;
}

The if statement first tests if a condition is true and then executes an instruction and the else is for when the result of the condition is false.

If you want to execute more than 1 instruction in an if statement then you have to put them between curly brackets. The curly brackets are used to group commands together.

#include

int main()
{
   int mark;
   char pass;
   scanf("%d" ,&mark);
   if (mark > 40)
   {
      pass = 'y';
      printf("You passed");
   }
   else
   {
      pass = 'n';
      printf("You failed");
   }
   return 0;
}

It is possible to test 2 or more conditions at once using the AND (&&) operator. You can use the OR ( || ) operator to test if 1 of 2 conditions is true. The NOT (!) operator makes a true result of a test false and vice versa.

#include

int main()
{
   int a,b;
   scanf("%d" ,&a);
   scanf("%d" ,&b);
   if (a > 0 && b > 0)
      printf("Both numbers are positive\n");
   if (a == 0 | | b == 0)
      printf("At least one of the numbers = 0\n");
   if (!(a > 0) && !(b > 0))
      printf("Both numbers are negative\n");
   return 0;
}

Boolean operators:

In the above examples we used > and < which are called boolean operators. They are called boolean operators because they give you either true or false when you use them to test a condition. The following is table of all the boolean operators in c:


















The switch statement:

The switch statement is just like an if statement but it has many conditions and the commands for those conditions in only 1 statement. It is runs faster than an if statement. In a switch statement you first choose the variable to be tested and then you give each of the conditions and the commands for the conditions. You can also put in a default if none of the conditions are equal to the value of the variable. If you use more than one command then you need to remember to group them between curly brackets.

#include

int main()
{
   char fruit;
   printf("Which one is your favourite fruit:\n");
   printf( "a ) Apples\n");
   printf( "b ) Bananas\n");
   printf( "c ) Cherries\n");
   scanf( "%c" ,&fruit);
   switch (fruit)
   {
      case 'a':
         printf("You like apples\n");
         break;
      case 'b':
         printf("You like bananas\n");
         break;
      case 'c':
         printf("You like cherries\n");
         break;
      default:
         printf("You entered an invalid choice\n");
   }
   return 0;
}


NEXT LESSON NO 4

Report An Error Or Mistake 





Monday, 1 September 2014

Learn C Programming Lesson 2 - Variables And Constants

BY Unknown IN , No comments


Learn C Programming Tutorial Lesson 2
Variables and Constants :

What are variables:

Variables in C are memory locations that are given names and can be assigned values. We use variables to store data in memory for later use. There are 2 basic kinds of variables in C which are numeric and character.

Numeric variables:

Numeric variables can either be integer values or they can be Real values. Integer values are whole numbers without a fraction part or decimal point in them. Real numbers can have a decimal point in them.

Character variables:

Character variables are letters of the alphabet as well as all characters on the ASCII chart and even the numbers 0 - 9. Characters must always be put between single quotes. A number put between single quotes is not the same thing as a number without them.

What are constants:

The difference between variables and constants is that variables can change their value at any time but constants can never change their value. Constants can be useful for items such as Pi or the charge on an electron. Using constants can stop you from changing the value of an item by mistake.

Declaring variables:

To declare a variable we first put the type of variable and then give the variable a name. The following is a table of the names of the types of variables as well as their ranges:













You can name a variable anything you like as long as it includes only letters, numbers or underscores and does not start with a number. It is a good idea to keep your variable names less than 32 characters long to save time on typing them out and for compiler compatibility reasons. Variables must always be declared at the top before any other commands are used. Now let's declare an integer variable called a and a character variable called b.

int main()
{
   int a;
   char b;
   return 0;
}

You can declare more than one variable at the same time in the following way:

int main()
{
   int a,b,c;
   return 0;
}

To declare a constant all you have to do it put the word const in front of a normal variable declaration and make assign a value to it.

int main()
{
   const float pi = 3.14;
   return 0;
}

Signed and unsigned variables:

The difference between signed and unsigned variables is that signed variables can be either negative or positive but unsigned variables can only be positive. By using an unsigned variable you can increase the maximum positive range. When you declare a variable in the normal way it is automatically a signed variable. To declare an unsigned variable you just put the word unsigned before your variable declaration or signed for a signed variable although there is no reason to declare a variable as signed since they already are.

int main()
{
   unsigned int a;
   signed int b;
   return 0;
}

Using variables in calculations:

To assign a value to a variable you use the equals sign.

int main()
{
   int a;
   char b;
   a = 3;
   b = 'H';
   return 0;
}

There are a few different operators that can be used when performing calculations which are listed in the following table:











To perform a calculation you need to have a variable to put the answer into. You can also use both variables and normal numbers in calculations.

int main()
{
   int a,b;
   a = 5;
   b = a + 3;
   a = a - 3;
   return 0;
}

Reading and printing variables:

You can read a variable from the keyboard with the scanf command and print a variable with the printf command.

#include

int main()

{
   int a;
   scanf("%d",&a);
   a = a * 2;
   printf("The answer is %d",&a);
   return 0;
}

The %d is for reading or printing integer values and there are others as shown in the following table:

















 PREVIOUS        START OVER        NEXT

Friday, 22 August 2014

Learn C Programming Lesson 1 - Hello World

BY Unknown IN , 2 comments


Learn C Programming Tutorial Lesson 1 - Hello World

What is C and why learn it ?

C was developed in the early 1970s by Dennis Ritchie at Bell Laboratories. C was originally designed for writing system software but today a variety of software programs are written in C. C can be used on many different types of computers but is mostly used with the UNIX operating system.

It is a good idea to learn C because it has been around for a long time which means there is a lot of information available on it. Quite a few other programming languages such as C++ and Java are also based on C which means you will be able to learn them more easily in the future.

What you will need:
This tutorial is written for both Windows and UNIX/Linux users. All the code in the examples has been tested and works the same on both operating systems.

If you are using Windows then you need to download borland C++ compiler from http://www.borland.com/cbuilder/cppcomp. Once you have downloaded and installed it you need to add "C:\Borland\BCC55\Bin" to your path. To add it to your path in Windows 95/98/ME you need to add the line "PATH=C:\Borland\BCC55\Bin" to c:\autoexec.bat using notepad. If you are using Windows NT/2000/XP then you need to open the control panel and then double click on "system". Click on the "Advanced" tab and then click "Environment Variables". Select the item called "Path" and then click "Edit". Add ";C:\Borland\BCC55\Bin" to "Variable value" in the dialog box that appears and then click OK and close everything.

All Windows users will now have to create a text file called "bcc32.cfg" in "C:\Borland\BCC55\Bin" and save the following lines of text in it:

-I"C:\Borland\BCC55\include"
-L"C:\Borland\BCC55\lib"

If you are using UNIX/Linux then you will most probably have a C compiler installed called GCC. To check if you have it installed type "cc" at the command prompt. If for some reason you don't have it then you can download it from http://gcc.gnu.org.

Your first program:
The first thing we must do is open a text editor. Windows users can use Notepad and UNIX/Linux users can use emacs or vi. Now type the following lines of code and then I will explain it. Make sure that you type it exactly as I have or else you will have problems. Also don't be scared if you think it is too complicated because it is all very easy once you understand it.

#include

int main()

{
   printf("Hello World\n");
   return 0;
}

#include
This includes a file called stdio.h which lets us use certain commands. stdio is short for Standard Input/Output which means it has commands for input like reading from the keyboard and output like printing things on the screen.

int main()
int is what is called the return value which will be explained in a while. main is the name of the point where the program starts and the brackets are there for a reason that you will learn in the future but they have to be there.

{}
The 2 curly brackets are used to group all the commands together so it is known that the commands belong to main. These curly brackets are used very often in C to group things together.

printf("Hello World\n");
This is the printf command and it prints text on the screen. The data that is to be printed is put inside brackets. You will also notice that the words are inside inverted commas because they are what is called a string. Each letter is called a character and a series of characters that is grouped together is called a string. Strings must always be put between inverted commas. The \n is called an escape sequence and represents a newline character and is used because when you press ENTER it doesn't insert a new line character but instead takes you onto the next line in the text editor. You have to put a semi-colon after every command to show that it is the end of the command.

Table of commonly used escape sequences:

















return 0;
The int in int main() is short for integer which is another word for number. We need to use the return command to return the value 0 to the operating system to tell it that there were no errors while the program was running. Notice that it is a command so it also has to have a semi-colon after it.

Save the text file as hello.c and if you are using Notepad make sure you select All Files from the save dialog or else you won't be able to compile your program.

You now need to open a command prompt. If you are using Windows then click Start->Run and type "command" and Click Ok. If you are using UNIX/Linux and are not using a graphical user interface then you will have to exit the text editor.

Using the command prompt, change to the directory that you saved your file in. Windows users must then type:

C:\>bcc32 hello.c
UNIX/Linux users must type:

$cc hello.c -ohello
The -o is for the output file name. If you leave out the -o then the file name a.out is used.

This will compile your C program. If you made any mistakes then it will tell you which line you made it on and you will have to type out the code again and this time make sure you do it exactly as I did it. If you did everything right then you will not see any error messages and your program will have been compiled into an exe. You can now run this program by typing "hello.exe" for Windows and "./hello" for UNIX/Linux.

You should now see the words "Hello World" printed on the screen. Congratulations! You have just made your first program in C.

Indentation:
You will see that the printf and return commands have been indented or moved away from the left side. This is used to make the code more readable. It seems like a stupid thing to do because it just wastes time but when you start writing longer, more complex programs, you will understand why indentation is needed.

Using comments:
Comments are a way of explaining what a program does. They are put after // or between /* */. Comments are ignored by the compiler and are used by you and other people to understand your code. You should always put a comment at the top of a program that tells you what the program does because one day if you come back and look at a program you might not be able to understand what it does but the comment will tell you. You can also use comments in between your code to explain a piece of code that is very complex. Here is an example of how to comment the Hello World program:

/* Author: Your name
   Date: yyyy/mm/dd
   Description:
   Writes the words "Hello World" on the screen */

#include


int main()

{
   printf("Hello World\n"); //prints "Hello World"
   return 0;


PREVIOUS        START OVER        NEXT >