Tuesday, March 15, 2011

Introduction
A Programing Language should be designed to support certain kind of data, such as numbers,characters,strings etc. To get useful output known as information. A program is a set of statements for a specific task, which will be executed in a sequential form. These statements/instructions are formed using certain words and symbols according to the rules known as syntax rules or grammar of the language. Every program must follow accurately the syntax rules supported by the language.

The C Character set
The characters used to form words,numbers and expressions depend upon the computer on which the program runs. The Characters in C are classified in to four categories.
1. Letters-------------> Ex: A to Z and a to z

2. Digits--------------> Ex: All decimal digits 0 to 9

3. White spaces--------> Ex: Blank space, Horizontal tab, Vertical tab, New line, Form feed

4. Special characters--> Ex:, . ; " ' ! | / \ ~ _ $ ? & ^ * - + < > ( ) [ ] { } % # = @

The C Keywords
The C keywords are reserved words by the compiler. All the C keywords have been assigned fixed meaning. The Keywords cannot be used as variable names because they have been assigned fixed jobs. However, few C compilers allow to construct variable names, which exactly coincides with the keywords. It is suggested not to mix up keywords with variable names.
Keywords:

auto-----break-----case----char----const----continue----default----do

double----else-----enum-----extern-------float--------for-----goto----if
int----long----register---return---short---signed----sizeof---static
struct----switch----typedef----union---unsigned---void---volatile----while
In addition to these standard keywords some more like asm,typeof,huge,interrupt,near,etc.
Identifiers
Identifiers are names of variables,functions, and arrays. They are user-defined names, consisting of sequence of letters and digits, with the letters as the first character. Lower case letters are preferred. However, the upper case letters are also permitted. The (_) under score symbol can be used as an identifier.
Examples:1. #define N 10 2. # define a 15

Here 'N' and 'a' are user-defined identifiers

Constants
The Constants in C are applicable to the values, which do not change during the execution of a program. There are several types of constants in C. They are

1. Numeric Constants

2. Character Constants

Numeric Constants
Numeric Constants Classifieds into several categories.They are

* Integer constants
These are the sequence of numbers from 0 to 9 without decimal points or fractional part or any other symbols. It requires minimum two bytes and maximum four bytes. Integer constants could either be positive or negative or maybe zero. The number without a sign is assumed as positive.

Example: 50,70,+80,-15 etc.

* Real constants
Real constants often as floating point constants. Integer constants are unfit to represent many quantities. Many parameters or quantities are defined not only in integers but also in real numbers. For example length, height, prize, distance etc. are measured in real numbers.

Example: 1.0,2.3450,3.14 etc.

The real constants can be written in exponential notation,which contains a fractional part and an exponential part. For example, the value 2456.123 can be written as 2.4561Xe+3.

The General format of the real number contains mantissa and an exponent. The mantissa is either a real number represented in decimal or an integer.The exponent is an integer number which may be positive or nagative. The letter 'e' separating the mantissa and exponent can be written in lower case or upper case.

Character Constants
* Single character constants:

A characteer constant is a single character. They are also represented with a single digit or a single special symbol or white space enclosed within a pair of single quote marks.

Example: 'a','d','m',etc.

* String constants:

String constants are sequence of characters enclosed within a double quote
marks. The string may be a combination of all kinds of symbols.

Example: "Hello","Sample","Ramana" etc.

Variables
A variable is a data name used for storing a data value. A variable is a name which is used for storing some value in it. Its value may be changed during the program execution of a program. A variable name may be declared based on the meaning of the operation.

Example: height,weight, average, sum, mul etc.

Rules for defining variables
1. They must begin with a character without spaces but underscore is permitted.

2. The length of the variable varies from compiler to compiler. Generally most of the compilers support 8 characters excluding extension. However, the ANSI standard recognizes the maximum length of a variable upto 31 characters.

3. The variable should not be a C keyword.

4. The variable names may be a combination of upper and lower characters. For example Sum and sum are not the same.

5. The variable name should not start with a digit.

Data Types
All C compilers support a variety of data types. This enables the programmer to select the appropriate data type as per the need of the application. Which type of data is storing in a variable is known as data type. Generally data is represented using numbers or characters. The numbers may be integers or real.

A C language programmer has to tell the system before-hand, the type of numbers or characters he is using in his program. These are data types. There are many data types in C language. A C programmer has to use appropriate data type as per his requirement.

C language data types can be broadly classified as

* Primary data type

* Derived data type

* User-defined data type
All C Compilers accept the following fundamental data types

1. Integer -------------------------------------> int

2. Character ----------------------------------> char

3. Floating Point ------------------------------> float

4. Double precision floating point------------> double

5. Void ---------------------------------------> void

The size and range of each data type is given in the below

* char -----------------------------------> -128 to 127

* int -----------------------------------> -32768 to +32767

* float ---------------------------------->3.4 e-38 to 3.4 e+38

* double --------------------------------> 1.7 e-308 to 1.7 e+308

Integer Type :
Integers are whole numbers with a machine dependent range of values. A good programming language as to support the programmer by giving a control on a range of numbers and storage space. C has 3 classes of integer storage namely short int, int and long int. All of these data types have signed and unsigned forms. A short int requires half the space than normal integer values. Unsigned numbers are always positive and consume all the bits for the magnitude of the number. The long and unsigned integers are used to declare a longer range of values.

Floating Point Types :
Floating point number represents a real number with 6 digits precision. Floating point numbers are denoted by the keyword float. When the accuracy of the floating point number is insufficient, we can use the double to define the number. The double is same as float but with longer precision. To extend the precision further we can use long double which consumes 80 bits of memory spaces.

Void Type :
Using void data type, we can specify the type of a function. It is a good practice to avoid functions that does not return any values to the calling function.

Character Type :
A single character can be defined as a defined as a character type of data. Characters are usually stored in 8 bits of internal storage. The qualifier signed or unsigned can be explicitly applied to char. While unsigned characters have values between 0 and 255, signed characters have values from –128 to 127.

Data types and their control strings

Data Type------------------->Size(bytes)--------->Range---------------------------->Control String

Char................................................ 1 ............................... -128 to 127............................................... %c

Unsigned Char............................... 1 ............................... 0 to 255...................................................... %c

Short or int................................... 2 ............................. -32,768 to 32,767 .................................... %i or %d

Unsigned int ................................. 2 .................................. 0 to 655355............................................... %u

Long................................................ 4 ................................. -2147483648 to 2147483647.................. %ld

Unsigned long............................... 4 ..................................... 0 to 4294967295................................. %lu

Float............................................... 4 .................................... 3.4e-38 to 3.4e+38.................. %f or %g

Double.............................................. 8 ................................... 1.7e-308 to 1.7e+308.......................... %lf

Long Double......................................... 10 .......................... 3.4e-4932 to 1.1e+4932.................. %lf
Have you always wanted to master a programming language. Well today if you are glancing at this page you have chosen a language which perhaps without doubt is the most versatile. But to learn C for say basic programmers is a challenge. While the old basic used interpreters C uses compilers and basically is very portable. But let quit all this jibrish and get to the heart of this page. I say you can learn C programming in 3 hours. Well atleast the basics that will help you to build more powerful programs.You say I can't show you C in 5 hours. Well let's test that ...


A simple hello program.(demonstrates the const function in all c programs--the main() function.)
(example-1)
main()
{
puts("hello world guess who is writing a c program");
return(0);
}

That's it. In all c programs there is a main function which is followed by a { and closed by a } after a return()function.It doesn't have to be return(0) but that depends upon the type of c compiler you have. Check your compiler before you start your programming.

You saw above that puts function is used to put a whole sentence on the screen; but are there functions that will put characters on the screen/take characters: Yes and next is a table of what they are and what they do. Read them and the examples that follow.

getchar() Gets a single character from the input/keyboard.
putchar() Puts a single character on the screen.
The printf function is a function used to print the output to the screen.printf() needs to know if the output is an integer,real,etc example-2
main()
{
printf(hello);
}
Assuming hello was defined earlier say by #define hello "Hello!" the output is Hello!. But if the output is an integer then %d has to be attatched to the printf statement.

This above can be shown as printf("I am %d years old",12) which will result in the following result:I am 12 years old

The %d tells that an integer is to be placed here.

Now we will look into a function called scanf().This lets you input from the kewyboard and for that input to be taken by the program and processed.Once again it is important to tell scanf() what type of data is being scanned.

Here is an example of a program that demonstrates both scanf and printf in unison.
example-3

main() {
int count;
puts("Please enter a number: ");
scanf("%d", &count);
printf("The number is %d",count);
}


That concludes the first hour of your tutorial.Now this is a list of data type identifiers.


%f=float %c=char %s =s tring %e=inputs number in scientific notation.


As you saw in the first hour of our tutorial c is a language in which you program using functions. Functions are usually identified by the following characteristic:>> functionname() In c the main() function is essential. Think of it as a constant function for all your programs and all other functions can be accessed from the main().Before I show you how we do that let us have an example where we want to pause a program before the screen is changed. This would involve the foll- owing procedure:>> write a main function then use puts function to put statements on the screen like we did in section 1 above and then before the next set of puts statements declare a pause.

This is how it is done:

example-4
main()
{
puts("hello there");
puts("what is your name?")
pause()
puts("It is nice to meet you")
}
pause();
{
int move_on;
printf("press entere to continue");
move_on=getchar();
return(0);
}

This above will pause until a key is pressed on the keyboard. Granted that the above program makes no sense from a practical point of view but I want to show is the use of another function inside the main function.

C has many functions that comes with it. See your compiler manual to see what you have.Now we are going to look at conditions in c programming:>> the if command and do command.

Here is an example of th if command:

example-5
main()
{
float cost,tax,luxury,total;
luxury=0.0;
printf("Enter the cost of the item: ");
scanf("%f", &cost);
tax=cost*0.06;
if(cost>40000.0)
luxury=cost*0.005;
total=cost+tax+luxury;
printf("the total cost is %0.2f",total);
}

This is a simple example of one if statement. Another If statement is the if -else statement. This can be shown as this

example-6
if(cost >40000)
{
luxury=cost*0.005;
printf("The luxury tax is %.2f",luxury);
}
else
{
puts("There is no luxury tax for the items");
luxury=0.0;
}

Now the format a do statement is as follows:

do
{
instruction;
instruction
}
while(condition);

The format for a FOR statement is as follows:

for(initial=value;condition;increment)
instruction;

Now for an example:

example-7
main()
{
int row,column;
puts("\t\tMY Handy multipication table");
for(row=1;tow<=10;row++)
{
for(column=1;column<=10;column++)
printf("%6d", row*column);
putchar('\n');
}
}

The output is a multipication table of 10x10 size.

example-8
main()
{
int temp;
float celsius;
char repeat;
do
{
printf("Input a temperature:");
scanf("%d", &temp);
celsius=(5.0/9.0)*(temp-32);
printf(%d degrees F is %6.2f degrees celsius\n",temp, celsius);
printf(("do you have another temperature?");
repeat=getchar();
putchar('\n');
}
while(repeat=='y'|| repeat=='y');
}

This shows you to how to use the do command for conditional programming in c.



Now we are in our 3rd hour. Now we will concentrate on arrays:

What is a flag?

A flag is an algorithm that informs the program that a certain condition has occured.

example-9

main()
{
int temp;
float celsius;
char repeat;
char flag;
do
{
flag='n";
do
{
if(flag=='n')
printf("Input a valid temperature :");
else
printf("input a valid temperature,stupid:");
scanf("%d",&temp);
flag='y';
}
while (temp<0||temp >100);
celsius=(5.0/9.0)*(temp-32);
printf("%d degrees F is %6.2f degrees celsius\n",temp,celsius);
printf("Do you have another temperature?");
repeat=getchar();
putchar('\n');
}
while (repeat=='y' || repeat=='Y");
}

That was an example of how flags work.

What is the break command?


The break command ends the loop in which it is placed just as if the while condition, or the condition in a for loop becomes false.

How to declare an array?

An array can be defined as follows:

int temp[5]={45,56,12,98,12};

This would mean the following:

temp[0]=45....temp[4]=12

This was a single dimension array with 5 elements of the integer type.If you wanted to depict float variables just use float temp instead of int temp.

Let us now see an example of using an array for two tasks.

main()
{
int temps[31];
int index,total;
float average,celsius;
total=0.0;
for(index=0;index<31;index++)
{
printf("enter temperature #%d:",index);
scanf("%d",&temps[index]);
}
for(index=0;index<31;index++)
total+=temps[index];
average=total/31.0
printf("average is:%f\n\n", average);
puts9"fahrenheit\tcelsius\n");
for(index=0;index<31;index++)
{
celsius=(5.0/9.0)*(temps[index]-32);
printf("%d\t\t%6.2f\n",temps[index],celsius);
}
}


Now I am going to show you how to pass an array. When you pass an array you are actually passing the address of the array.

example-10

#define count 31
main()
{
int temps[count];
int index;
float celsius;
for(index=0; index< count;index++)
{
celsius=(5.0/9.0)*(heat[index]-32);
printf("%d\t\t%6.2f\n",heat[index],celsius);
}
}




Now we are in the fourth hour of our tutorial.We are now going to look at 1)comparing strings 2)determining string lengths. 3) combining strings 4)structures.
Comparing 2 strings:>> In c it is not possible to directly compare two strings so a statement like if (string1==string2) is not valid.

Most c libraries contain a function called the strcmp().This is used to compare two strings in the following manner.

if(strcmp(name1,name2)==0)
puts("The names are the same");
else
puts("The names are not the same.");

Determining string length.:>> This is done using the strlen() function.


a simple programming bit showing this function looks like this:


gets(name);
count=strlen(name);
printf("the string %s has %d characters",name,count);


Combining strings:>>We use the function strcpy() an example follows:

Example-11


strcpy(name,"Adam");
strcpy(name1,"and eve");
strcat(name,name1);
puts(name);


The assumption being that adam and eve are two values of the variables name1 and name2. The end result is the combination of the 2 names.

What are structures?

A structure variable is a collection of other variables comprising different types.

What are pointers?


Ponters are variables which refer to the memory locations of other variables.

This is how a structure is defined.

example-12


struct cd
{
char name[20];
char description[40];
char category[12];
float cost;
int number;
};
main()

Notice how the main function comes after the definition of the structure. In the example above the cd was a cd disk and I was writing the definition of a cd collection program.



Now in the fifth hour I will show you how to output your data onto a disk.After all what is the use of the program if you can't save output to a disk.

Inorder to do this we have to use a pointer. The pointer in this case is FILE. The syntax to declare a file is :FILE*file_ponter;

The link between your program, the file and the computer is established with the fopen() function using the syntax shown below:
pointer=fopen("FILENAME","mode");


For example to create a file by the name cd.dat we do the following:

FILE*cdfile;
cdfile=fopen("CD>DAT","w");
If you will be reading from the file above use "r" instead "w" in the
second sentence.

In order to rpint information use the following command:
FILE*cdfile;
cdfile=fopen("PRN","w");
A file is closed by using the fclose() command.Next we will look at an exam ple of reading from a file.

example-13

#include "stdio.h"
main()
{
FILE*fp;
int letter;
if((fp=fopen("MYFILE","r"))==NULL)
{
puts("Cannot oepn the file");
exit();
}
while((letter=fgetc(fp)) !=eof)
printf("%c",letter);
fclose(fp);
}

The eof statement means end of file and this is included in the stdio.h header file which was declared at the start of the example. The stdio.h header file is one of many that comes with your compiler. So check your compiler specifics for other header files which will help perform other functions.

Now that you went through this tutorial you should be in a position to write simple programs and save it to a disk so you can give it your friends or even your boss. In no way the depth of c can be done in 5 hours but the nut and bolts can be learned that fast.Wher e you go from there depends upon your ambitions and hard work.