|
|
A Unit of Aim Clear Technologies Ltd.
Advertise with us
 |
|
neha
Marketing Executive
Joined:
Mon Aug 24, 2009 10:57 pm
Beans: 767
In Bank: 10965
College: IET
Degree: B.E
Position: Teacher
|
|
Sat Sep 19, 2009 6:17 pm
|
Post subject: C Programming Tutorials
Basic Introduction C is a general-purpose high level language that was originally developed by Dennis Ritchie for the Unix operating system. It was first implemented on the Digital Equipment Corporation PDP-11 computer in 1972.
The Unix operating system and virtually all Unix applications are written in the C language. C has now become a widely used professional language for various reasons.
Easy to learn
Structured language
It produces efficient programs.
It can handle low-level activities.
It can be compiled on a variety of computers.
Facts about C
C was invented to write an operating system called UNIX.
C is a successor of B language which was introduced around 1970
The language was formalized in 1988 by the American National Standard Institute (ANSI).
By 1973 UNIX OS almost totally written in C.
Today C is the most widely used System Programming Language.
Most of the state of the art software have been implemented using C
Why to use C ? C was initially used for system development work, in particular the programs that make-up the operating system. C was adopted as a system development language because it produces code that runs nearly as fast as code written in assembly language. Some examples of the use of C might be:
Operating Systems
Language Compilers
Assemblers
Text Editors
Print Spoolers
Network Drivers
Modern Programs
Data Bases
Language Interpreters
Utilities
C Program File All the C programs are written into text files with extension ".c" for example hello.c. You can use "vi" editor to write your C program into a file.
This tutorial assumes that you know how to edit a text file and how to write programming instructions inside a program file.
C Compilers When you write any program in C language then to run that program you need to compile that program using a C Compiler which converts your program into a language understandable by a computer. This is called machine language (ie. binary format). So before proceeding, make sure you have C Compiler available at your computer. It comes along with all flavors of Unix and Linux.
If you are working over Unix or Linux then you can type gcc -v or cc -v and check the result. You can ask your system administrator or you can take help from anyone to identify an available C Compiler at your computer.
If you don't have C compiler installed at your computer then you can use below given link to download a GNU C Compiler and use it
|
|
|
|
neha
Marketing Executive
Joined:
Mon Aug 24, 2009 10:57 pm
Beans: 767
In Bank: 10965
College: IET
Degree: B.E
Position: Teacher
|
|
Sat Sep 19, 2009 6:19 pm
|
Post subject: Re: C Programming Tutorials
Program Structure A C program basically has the following form:
Preprocessor Commands
Functions
Variables
Statements & Expressions
Comments
The following program is written in the C programming language. Open a text file hello.c using vi editor and put the following lines inside that file.
#include <stdio.h>
int main() { /* My first program */ printf("Hello, TechPreparation! \n");
return 0; }
Preprocessor Commands: These commands tells the compiler to do preprocessing before doing actual compilation. Like #include <stdio.h> is a preprocessor command which tells a C compiler to include stdio.h file before going to actual compilation. You will learn more about C Preprocessors in C Preprocessors session.
Functions: Functions are main building blocks of any C Program. Every C Program will have one or more functions and there is one mandatory function which is called main() function. This function is prefixed with keyword int which means this function returns an integer value when it exits. This integer value is returned using return statement.
The C Programming language provides a set of built-in functions. In the above example printf() is a C built-in function which is used to print anything on the screen.
Variables: Variables are used to hold numbers, strings and complex data for manipulation. You will learn in detail about variables in C Variable Types.
Statements & Expressions : Expressions combine variables and constants to create new values. Statements are expressions, assignments, function calls, or control flow statements which make up C programs.
Comments: Comments are used to give additional useful information inside a C Program. All the comments will be put inside /*...*/ as given in the example above. A comment can span through multiple lines.
Note the followings
C is a case sensitive programming language. It means in C printf and Printf will have different meanings.
C has a free-form line structure. End of each C statement must be marked with a semicolon.
Multiple statements can be one the same line.
White Spaces (ie tab space and space bar ) are ignored.
Statements can continue over multiple lines.
C Program Compilation To compile a C program you would have to Compiler name and program files name. Assuming your compiler's name is cc and program file name is hello.c, give following command at Unix prompt.
$cc hello.c This will produce a binary file called a.out and an object file hello.o in your current directory. Here a.out is your first program which you will run at Unix prompt like any other system program. If you don't like the name a.out then you can produce a binary file with your own name by using -o option while compiling C program. See an example below
$cc -o hello hello.c Now you will get a binary with name hello. Execute this program at Unix prompt but before executing / running this program make sure that it has execute permission set. If you don't know what is execute permission then just follow these two steps
$chmod 755 hello $./hello
This will produce following result Hello, TechPreparation! Congratulations!! you have written your first program in "C". Now believe me its not difficult to learn "C".
|
|
|
|
neha
Marketing Executive
Joined:
Mon Aug 24, 2009 10:57 pm
Beans: 767
In Bank: 10965
College: IET
Degree: B.E
Position: Teacher
|
|
Sat Sep 19, 2009 6:20 pm
|
Post subject: Re: C Programming Tutorials
Basic Datatypes
C has a concept of 'data types' which are used to define a variable before its use. The definition of a variable will assign storage for the variable and define the type of data that will be held in the location.
The value of a variable can be changed any time.
C has the following basic built-in datatypes.
int
float
double
char
Please note that there is not a Boolean data type. C does not have the traditional view about logical comparison, but that's another story.
int - data type int is used to define integer numbers.
{ int Count; Count = 5; } float - data type float is used to define floating point numbers.
{ float Miles; Miles = 5.6; } double - data type double is used to define BIG floating point numbers. It reserves twice the storage for the number. On PCs this is likely to be 8 bytes.
{ double Atoms; Atoms = 2500000; } char - data type char defines characters.
{ char Letter; Letter = 'x'; } Modifiers The data types explained above have the following modifiers.
short
long
signed
unsigned
The modifiers define the amount of storage allocated to the variable. The amount of storage allocated is not cast in stone. ANSI has the following rules:
short int <= int <= long int float <= double <= long double What this means is that a 'short int' should assign less than or the same amount of storage as an 'int' and the 'int' should be less or the same bytes than a 'long int'. What this means in the real world is:
Type Bytes Range short int 2 -32,768 -> +32,767 (32kb) unsigned short int 2 0 -> +65,535 (64Kb) unsigned int 4 0 -> +4,294,967,295 ( 4Gb) int 4 -2,147,483,648 -> +2,147,483,647 ( 2Gb) long int 4 -2,147,483,648 -> +2,147,483,647 ( 2Gb) signed char 1 -128 -> +127 unsigned char 1 0 -> +255 float 4 double 8 long double 12 These figures only apply to today's generation of PCs. Mainframes and midrange machines could use different figures, but would still comply with the rule above.
You can find out how much storage is allocated to a data type by using the sizeof operator discussed in Operator Types Session.
|
|
|
|
neha
Marketing Executive
Joined:
Mon Aug 24, 2009 10:57 pm
Beans: 767
In Bank: 10965
College: IET
Degree: B.E
Position: Teacher
|
|
Sat Sep 19, 2009 6:22 pm
|
Post subject: Re: C Programming Tutorials
Qualifiers
A type qualifier is used to refine the declaration of a variable, a function, and parameters, by specifying whether:
The value of a variable can be changed.
The value of a variable must always be read from memory rather than from a register
Standard C language recognizes the following two qualifiers:
const
volatile
The const qualifier is used to tell C that the variable value can not change after initialization. const float pi=3.14159;
Now pi cannot be changed at a later time within the program.
Another way to define constants is with the #define preprocessor which has the advantage that it does not use any storage
The volatile qualifier declares a data type that can have its value changed in ways outside the control or detection of the compiler (such as a variable updated by the system clock or by another program). This prevents the compiler from optimizing code referring to the object by storing the object's value in a register and re-reading it from there, rather than from memory, where it may have changed. You will use this qualifier once you will become expert in "C". So for now just proceed.
What are Arrays: We have seen all basic data types. In C language it is possible to make arrays whose elements are basic types. Thus we can make an array of 10 integers with the declaration.
int x[10]; The square brackets mean subscripting; parentheses are used only for function references. Array indexes begin at zero, so the elements of x are:
Thus Array are special type of variables which can be used to store multiple values of same data type. Those values are stored and accessed using subscript or index.
Arrays occupy consecutive memory slots in the computer's memory.
x[0], x[1], x[2], ..., x[9] If an array has n elements, the largest subscript is n-1.
Multiple-dimension arrays are provided. The declaration and use look like:
int name[10] [20]; n = name[i+j] [1] + name[k] [2]; Subscripts can be arbitrary integer expressions. Multi-dimension arrays are stored by row so the rightmost subscript varies fastest. In above example name has 10 rows and 20 columns.
Same way, arrays can be defined for any data type. Text is usually kept as an array of characters. By convention in C, the last character in a character array should be a `\0' because most programs that manipulate character arrays expect it. For example, printf uses the `\0' to detect the end of a character array when printing it out with a `%s'.
Here is a program which reads a line, stores it in a buffer, and prints its length (excluding the newline at the end).
main( ) { int n, c; char line[100]; n = 0; while( (c=getchar( )) != '\n' ) { if( n < 100 ) line[n] = c; n++; } printf("length = %d\n", n); } Array Initialization
As with other declarations, array declarations can include an optional initialization
Scalar variables are initialized with a single value
Arrays are initialized with a list of values
The list is enclosed in curly braces
int array [8] = {2, 4, 6, 8, 10, 12, 14, 16}; The number of initializes cannot be more than the number of elements in the array but it can be less in which case, the remaining elements are initialized to 0.if you like, the array size can be inferred from the number of initializes by leaving the square brackets empty so these are identical declarations:
int array1 [8] = {2, 4, 6, 8, 10, 12, 14, 16}; int array2 [] = {2, 4, 6, 8, 10, 12, 14, 16}; An array of characters ie string can be initialized as follows:
char string[10] = "Hello";
|
|
|
|
neha
Marketing Executive
Joined:
Mon Aug 24, 2009 10:57 pm
Beans: 767
In Bank: 10965
College: IET
Degree: B.E
Position: Teacher
|
|
Sat Sep 19, 2009 6:23 pm
|
Post subject: Re: C Programming Tutorials
Variable Types
A variable is just a named area of storage that can hold a single value (numeric or character). The C language demands that you declare the name of each variable that you are going to use and its type, or class, before you actually try to do anything with it.
The Programming language C has two main variable types
Local Variables
Global Variables
Local Variables
Local variables scope is confined within the block or function where it is defined. Local variables must always be defined at the top of a block.
When a local variable is defined - it is not initialized by the system, you must initialize it yourself.
When execution of the block starts the variable is available, and when the block ends the variable 'dies'.
Check following example's output
main() { int i=4; int j=10;
i++;
if (j > 0) { /* i defined in 'main' can be seen */ printf("i is %d\n",i); }
if (j > 0) { /* 'i' is defined and so local to this block */ int i=100; printf("i is %d\n",i); }/* 'i' (value 100) dies here */
printf("i is %d\n",i); /* 'i' (value 5) is now visable.*/ }
This will generate following output i is 5 i is 100 i is 5 Here ++ is called incremental operator and it increase the value of any integer variable by 1. Thus i++ is equivalent to i = i + 1;
You will see -- operator also which is called decremental operator and it decrease the value of any integer variable by 1. Thus i-- is equivalent to i = i - 1;
Global Variables Global variable is defined at the top of the program file and it can be visible and modified by any function that may reference it.
Global variables are initialized automatically by the system when you define them!
Data Type Initialser int 0 char '\0' float 0 pointer NULL If same variable name is being used for global and local variable then local variable takes preference in its scope. But it is not a good practice to use global variables and local variables with the same name.
int i=4; /* Global definition */
main() { i++; /* Global variable */ func(); printf( "Value of i = %d -- main function\n", i ); }
func() { int i=10; /* Local definition */ i++; /* Local variable */ printf( "Value of i = %d -- func() function\n", i ); }
This will produce following result Value of i = 11 -- func() function Value of i = 5 -- main function i in main function is global and will be incremented to 5. i in func is internal and will be incremented to 11. When control returns to main the internal variable will die and and any reference to i will be to the global.
|
|
|
|
neha
Marketing Executive
Joined:
Mon Aug 24, 2009 10:57 pm
Beans: 767
In Bank: 10965
College: IET
Degree: B.E
Position: Teacher
|
|
Sat Sep 19, 2009 6:24 pm
|
Post subject: Re: C Programming Tutorials
Storage Classes
A storage class defines the scope (visibility) and life time of variables and/or functions within a C Program.
There are following storage classes which can be used in a C Program
auto
register
static
extern
auto - Storage Class auto is the default storage class for all local variables.
{ int Count; auto int Month; } The example above defines two variables with the same storage class. auto can only be used within functions, i.e. local variables.
register - Storage Class register is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and cant have the unary '&' operator applied to it (as it does not have a memory location).
{ register int Miles; } Register should only be used for variables that require quick access - such as counters. It should also be noted that defining 'register' goes not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register - depending on hardware and implementation restrictions.
static - Storage Class static is the default storage class for global variables. The two variables below (count and road) both have a static storage class.
static int Count; int Road;
{ printf("%d\n", Road); } static variables can be 'seen' within all functions in this source file. At link time, the static variables defined here will not be seen by the object modules that are brought in.
static can also be defined within a function. If this is done the variable is initialized at run time but is not reinitialized when the function is called. This inside a function static variable retains its value during various calls.
void func(void);
static count=10; /* Global variable - static is the default */
main() { while (count--) { func(); }
}
void func( void ) { static i = 5; i++; printf("i is %d and count is %d\n", i, count); }
This will produce following result
i is 6 and count is 9 i is 7 and count is 8 i is 8 and count is 7 i is 9 and count is 6 i is 10 and count is 5 i is 11 and count is 4 i is 12 and count is 3 i is 13 and count is 2 i is 14 and count is 1 i is 15 and count is 0 static variables can be 'seen' within all functions in this source file. At link time, the static variables defined here will not be seen by the object modules that are brought in.
static can also be defined within a function. If this is done the variable is initialized at run time but is not reinitialized when the function is called. This inside a function static variable retains its value during various calls.
void func(void);
static count=10; /* Global variable - static is the default */
main() { while (count--) { func(); }
}
void func( void ) { static i = 5; i++; printf("i is %d and count is %d\n", i, count); }
This will produce following result
i is 6 and count is 9 i is 7 and count is 8 i is 8 and count is 7 i is 9 and count is 6 i is 10 and count is 5 i is 11 and count is 4 i is 12 and count is 3 i is 13 and count is 2 i is 14 and count is 1 i is 15 and count is 0 NOTE : Here keyword void means function does not return anything and it does not take any parameter. You can memories void as nothing. static variables are initialized to 0 automatically.
Definition vs. Declaration : Before proceeding, let us understand the difference between definition and declaration of a variable or function. Definition means where a variable or function is defined in reality and actual memory is allocated for variable or function. Declaration means just giving a reference of a variable and function. Through declaration we assure to the complier that this variable or function has been defined somewhere else in the program and will be provided at the time of linking. In the above examples char *func(void) has been put at the top which is a declaration of this function where as this function has been defined below to main() function.
There is one more very important use for 'static'. Consider this bit of code.
char *func(void);
main() { char *Text1; Text1 = func(); }
char *func(void) { char Text2[10]="martin"; return(Text2); } Now, 'func' returns a pointer to the memory location where 'text2' starts BUT text2 has a storage class of 'auto' and will disappear when we exit the function and could be overwritten but something else. The answer is to specify
static char Text[10]="martin"; The storage assigned to 'text2' will remain reserved for the duration if the program.
extern - Storage Class extern is used to give a reference of a global variable that is visible to ALL the program files. When you use 'extern' the variable cannot be initialized as all it does is point the variable name at a storage location that has been previously defined.
When you have multiple files and you define a global variable or function which will be used in other files also, then extern will be used in another file to give reference of defined variable or function. Just for understanding extern is used to declare a global variable or function in another files.
File 1: main.c
int count=5;
main() { write_extern(); } File 2: write.c
void write_extern(void);
extern int count;
void write_extern(void) { printf("count is %i\n", count); } Here extern keyword is being used to declare count in another file.
Now compile these two files as follows
gcc main.c write.c -o write This fill produce write program which can be executed to produce result.
Count in 'main.c' will have a value of 5. If main.c changes the value of count - write.c will see the new value
|
|
|
|
neha
Marketing Executive
Joined:
Mon Aug 24, 2009 10:57 pm
Beans: 767
In Bank: 10965
College: IET
Degree: B.E
Position: Teacher
|
|
Sat Sep 19, 2009 6:25 pm
|
Post subject: Re: C Programming Tutorials
Using Constants
A C constant is usually just the written version of a number. For example 1, 0, 5.73, 12.5e9. We can specify our constants in octal or hexadecimal, or force them to be treated as long integers.
Octal constants are written with a leading zero - 015.
Hexadecimal constants are written with a leading 0x - 0x1ae.
Long constants are written with a trailing L - 890L.
Character constants are usually just the character enclosed in single quotes; 'a', 'b', 'c'. Some characters can't be represented in this way, so we use a 2 character sequence as follows.
'\n' newline '\t' tab '\\' backslash '\'' single quote '\0' null ( Used automatically to terminate character string ) In addition, a required bit pattern can be specified using its octal equivalent.
'\044' produces bit pattern 00100100.
Character constants are rarely used, since string constants are more convenient. A string constant is surrounded by double quotes eg "Brian and Dennis". The string is actually stored as an array of characters. The null character '\0' is automatically placed at the end of such a string to act as a string terminator.
A character is a different type to a single character string. This is important point to note.
Defining Constants ANSI C allows you to declare constants. When you declare a constant it is a bit like a variable declaration except the value cannot be changed.
The const keyword is to declare a constant, as shown below:
int const a = 1; const int a =2; Note: You can declare the const before or after the type. Choose one an stick to it. It is usual to initialize a const with a value as it cannot get a value any other way.
The preprocessor #define is another more flexible (see Preprocessor Chapters) method to define constants in a program.
#define TRUE 1 #define FALSE 0 #define NAME_SIZE 20 Here TRUE, FALSE and NAME_SIZE are constant
You frequently see const declaration in function parameters. This says simply that the function is not going to change the value of the parameter.
The following function definition used concepts we have not met (see chapters on functions, strings, pointers, and standard libraries) but for completeness of this section it is is included here:
void strcpy(char *buffer, char const *string) The enum Data type enum is the abbreviation for ENUMERATE, and we can use this keyword to declare and initialize a sequence of integer constants. Here's an example:
enum colors {RED, YELLOW, GREEN, BLUE}; I've made the constant names uppercase, but you can name them which ever way you want.
Here, colors is the name given to the set of constants - the name is optional. Now, if you don't assign a value to a constant, the default value for the first one in the list - RED in our case, has the value of 0. The rest of the undefined constants have a value 1 more than the one before, so in our case, YELLOW is 1, GREEN is 2 and BLUE is 3.
But you can assign values if you wanted to:
enum colors {RED=1, YELLOW, GREEN=6, BLUE }; Now RED=1, YELLOW=2, GREEN=6 and BLUE=7.
The main advantage of enum is that if you don't initialize your constants, each one would have a unique value. The first would be zero and the rest would then count upwards.
You can name your constants in a weird order if you really wanted...
#include <stdio.h>
int main() { enum {RED=5, YELLOW, GREEN=4, BLUE};
printf("RED = %d\n", RED); printf("YELLOW = %d\n", YELLOW); printf("GREEN = %d\n", GREEN); printf("BLUE = %d\n", BLUE); return 0; }
This will produce following results
RED = 5 YELLOW = 6 GREEN = 4 BLUE = 5
|
|
|
|
neha
Marketing Executive
Joined:
Mon Aug 24, 2009 10:57 pm
Beans: 767
In Bank: 10965
College: IET
Degree: B.E
Position: Teacher
|
|
Sat Sep 19, 2009 6:26 pm
|
Post subject: Re: C Programming Tutorials
Bitwise Operators:
Bitwise operator works on bits and perform bit by bit operation.
Assume if B = 60; and B = 13; Now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1000
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011 Show Examples
|
|
|
|
neha
Marketing Executive
Joined:
Mon Aug 24, 2009 10:57 pm
Beans: 767
In Bank: 10965
College: IET
Degree: B.E
Position: Teacher
|
|
Sat Sep 19, 2009 6:27 pm
|
Post subject: Re: C Programming Tutorials
Flow Control Statements
C provides two styles of flow control:
Branching
Looping
Branching is deciding what actions to take and looping is deciding how many times to take a certain action.
Branching: Branching is so called because the program chooses to follow one branch or another.
if statement This is the most simple form of the branching statements.
It takes an expression in parenthesis and an statement or block of statements. if the expression is true then the statement or block of statements gets executed otherwise these statements are skipped.
NOTE: Expression will be assumed to be true if its evaluated values is non-zero.
if statements take the following form: Show Example
if (expression) statement;
or
if (expression) { Block of statements; }
or
if (expression) { Block of statements; } else { Block of statements; }
or
if (expression) { Block of statements; } else if(expression) { Block of statements; } else { Block of statements; } ? : Operator The ? : operator is just like an if ... else statement except that because it is an operator you can use it within expressions.
? : is a ternary operator in that it takes three values, this is the only ternary operator C has.
? : takes the following form: Show Example
if condition is true ? then X return value : otherwise Y value; switch statement: The switch statement is much like a nested if .. else statement. Its mostly a matter of preference which you use, switch statement can be slightly more efficient and easier to read. Show Example
switch( expression ) { case constant-expression1: statements1; [case constant-expression2: statements2;] [case constant-expression3: statements3;] [default : statements4;] } Using break keyword: If a condition is met in switch case then execution continues on into the next case clause also if it is not explicitly specified that the execution should exit the switch statement. This is achieved by using break keyword. What is default condition: If none of the listed conditions is met then default condition executed.
|
|
|
|
neha
Marketing Executive
Joined:
Mon Aug 24, 2009 10:57 pm
Beans: 767
In Bank: 10965
College: IET
Degree: B.E
Position: Teacher
|
|
Sat Sep 19, 2009 6:30 pm
|
Post subject: Re: C Programming Tutorials
Looping
Loops provide a way to repeat commands and control how many times they are repeated. C provides a number of looping way.
while loop The most basic loop in C is the while loop. A while statement is like a repeating if statement. Like an If statement, if the test condition is true: the statements get executed. The difference is that after the statements have been executed, the test condition is checked again. If it is still true the statements get executed again. This cycle repeats until the test condition evaluates to false.
Basic syntax of while loop is as follows: Show Example
while ( expression ) { Single statement or Block of statements; } for loop for loop is similar to while, it's just written differently. for statements are often used to process lists such a range of numbers:
Basic syntax of for loop is as follows: Show Example
for( expression1; expression2; expression3) { Single statement or Block of statements; } In the above syntax:
expression1 - Initializes variables.
expression2 - Conditional expression, as long as this condition is true, loop will keep executing.
expression3 - expression3 is the modifier which may be simple increment of a variable.
do...while loop do ... while is just like a while loop except that the test condition is checked at the end of the loop rather than the start. This has the effect that the content of the loop are always executed at least once.
Basic syntax of do...while loop is as follows: Show Example
do { Single statement or Block of statements; }while(expression); break and continue statements C provides two commands to control how we loop:
break -- exit form loop or switch.
continue -- skip 1 iteration of loop.
You already have seen example of using break statement. Here is an example showing usage of continue statement.
#include
main() { int i; int j = 10;
for( i = 0; i <= j; i ++ ) { if( i == 5 ) { continue; } printf("Hello %d\n", i ); } } This will produce following output:
Hello 0 Hello 1 Hello 2 Hello 3 Hello 4 Hello 6 Hello 7 Hello 8 Hello 9 Hello 10
|
|
|
|
Bookmark & Share
Who is online |
Users browsing this forum: No registered users and 0 guests |
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot post attachments in this forum
|

| |