Thursday 7 July 2011

C Language fundamentals

high-level programming language:A programming language such as C, FORTRAN, or Pascal that enables a programmer to write programs that are more or less independent of a particular type of computer. Such languages are considered high-level because they are closer to human languages and further from machine languages. In contrast, assembly languages are considered low-level because they are very close to machine languages. The main advantage of high-level languages over low-level languages is that they are easier to read, write, and maintain. Ultimately, programs written in a high-level language must be translated into machine language by a compiler or interpreter. The first high-level programming languages were designed in the 1950s. Now there are dozens of different languages, including Ada, Algol, BASIC, COBOL, C, C++, FORTRAN, LISP, Pascal, and Prolog.
Compiler:A compiler is a computer program (or set of programs) that transforms source code written in a programming language (the source language) into another computer language (the target language, often having a binary form known as object code). The most common reason for wanting to transform source code is to create an executable program.The name "compiler" is primarily used for programs that translate source code from a high-level programming language to a lower level language (e.g., assembly language or machine code). If the compiled program can run on a computer whose CPU or operating system is different from the one on which the compiler runs, the compiler is known as a cross-compiler. A program that translates from a low level language to a higher level one is a decompiler. A program that translates between high-level languages is usually called a language translator, source to source translator, or language converter. A language rewriter is usually a program that translates the form of expressions without a change of language.
Interpreter:In computer science, an interpreter normally means a computer program that executes, i.e. performs, instructions written in a programming language. An interpreter may be a program that either
1. executes the source code directly
2. translates source code into some efficient intermediate representation (code) and immediately executes this
3. explicitly executes stored precompiled code[1] made by a compiler which is part of the interpreter system
Perl, Python, MATLAB, and Ruby are examples of type 2, while UCSD Pascal is type 3: Source programs are compiled ahead of time and stored as machine independent code, which is then linked at run-time and executed by an interpreter and/or compiler (for JIT systems). Some systems, such as Smalltalk, BASIC, Java and others, may also combine 2 and 3.While interpreting and compiling are the two main means by which programming languages are implemented, these are not fully distinct categories, one of the reasons being that most interpreting systems also perform some translation work, just like compilers. The terms "interpreted language" or "compiled language" merely mean that the canonical implementation of that language is an interpreter or a compiler; a high level language is basically an abstraction which is (ideally) independent of particular implementations.
History of ‘C’
C was created by Dennis Ritchie at the Bell Laboratories in early 1970s. It was initially implemented on a system that used the UNIX operating system. C was the result of a development process which started with an older language BCPL, developed by Martin Richards. BCPL influenced a language B, written by Ken Thompson, which was the predecessor of C. BCPL and B were typeless languages whereas C provides a variety of data types. The fundamental type are characters, integers and floating point numbers of several sizes.Though, it has been closely asociated with the UNIX system. C is not tied to any one operating system or machine. It has been used equally well to write major programs in many different domains.
Evolution of ‘C’

Features of C
a) Middle Level Language : C is thought of as a middle level language because it combines elements of high-level language with the functionalism of assembly language. C allows manipulation of bits, bytes and addresses - the basic elements with which the computer functions. Also, C code is very portable, that is software written on one type of computer can be adapted to work on another type. Although C has five basic built-in data types, it is not strongly typed language as compared to high level languages, C permits almost all data type conversions. It allows direct manipulation of bits, bytes, words, and pointers. Thus, it is ideal for system level-programming.
b) Structured Language : The term block structured language does not apply strickly to C. Technically, a block-structured language permits procedures and function to be declared inside other procedures or functions. C does not allow creation of functions, within functions, and therefore cannot formally be called a block-structured language. However, it is referred to as a structured language because it is similar in many ways to other structured languages like ALGOL, Pascal and the likes.C allows compartmentalisation of code and data. This is a distinguishing feature of any structured language. It refers to the ability of a language to section off and hide all information and instructions necessary to perform a specific task from the rest of the program. Code can be compartmentalised in C using functions or code blocks. Functions are used to define and code separately, special tasks required in a program. This allows programs to be modular. Code block is a logically connected group of program statements that is treated like a unit. A code block is created by placing a sequence of statements between opening and closing curly braces.
c) Machine Independent (Portability of Code) : The code written in c is machine independent which means, there is no change in ‘C’ instructions, when you change the Operating System or Hardware. There is hardly any change required to compile when you move the program from one environment to another.Eg. Program written in DOS Operating System can be easily compiled on UNIX operating system by copying the source code on to the UNIX operating system and compiling it over there.
d) Fast Speed ( Better Performance ) : The execution speed of programs written in C is very fast since the statements are converted to few machine instructions which directly go into the processor for implementing the task.
e) Keywords with Libraries : The Original ‘C’ ( developed by Dennis Ritche ) is having only 32 keywords to perform all tasks which sometimes makes programming very tedious. But now we have ready made libraries of functions which can be used to perform simple tasks very easily without much of the coding. Library functions like printf() and scanf() can be used for Input and Output, they belong to stdio (Standard Input Output ) library.
f. Compiler Language : C Language uses COMPILER to translate your instruction code to machine code. Compiler takes the text source code and coverts to object code and then Linker ( part of compiler only ) converts it to executable code by taking reference of Library.


The various well-known compilers available for C are
o Turbo C
o Borland C
o Microsoft C
Note : Though there is only small difference in all these compilers, Let’s make it clear that this tutorial will deal with Turbo C 2.0
A simple ‘c’ program
/* my first c program */
main()
{
printf("hello world");
}
In Turbo C compiler following shortcut keys are used
Keys Operation
F9 Compile Only
Ctrl F9 Compile & run
Alt F5 To see Output Screen
F2 Save the File
Alt X Exit Turbo C
F3 Load File
Alt F3 Pick File from List

Explaination of the program written above :
; as statement terminator : In C ‘;’ is used as statement terminator. That means we can write as many statements as we want on a single line since statement is not terminated with new line character.
Case sensitive : C is very sensitive as far as Case is concerned. var & VAR are two different entities in c. One should remember in what case the variable were declared. For convenience everything is declared in lower case only.
Starts with main() function
Block of statements ( ‘{‘ for beginning of block & ‘}’ for end of block )
/* */ for writing comments in program.
main()
{
printf("C was developed");
printf("\nDennis Ritchie");
}

Escape Sequences

Character Meaning Example Output
\n New line Hello \nWorld Hello
World
\t Tab Hello \tWorld Hello World
\r Return Hello \rMe Mello
\a Alert ( beep sound ) Hello \aworld Hello world
\0 Null Hello \0 World Hello
Datatypes

Datatype Size (in bytes) Range Data
int 2 -2^15 to 2^15-1 Any non fractional value
char 1 -2^7 to 2 Any single ASCII character
float 4 No specific range Any Fractional value
long 4 -2^31 to 2^31-1 A number which is larger than int
double 8 -2^63 to 2^63 -1 Largest capacity datatype with fraction values also.
Format Specifiers
Format Specifier Used For getting appropriate output
%d Integer Decimal ( non fractional number )
%c Character
%f Float
%l Long
%s String
%lf For presenting double data
Input / Output Functions
Unformatted functions

getch() Waits for user to press any key, returns the key pressed that can be assigned to variable
getche() like getch() but echoes character pressed to screen
getchar() Accepts one character from user, terminates only when user presses enter. Even if user typed more than one character return first one character only.
putchar() can pass character type parameter, a single character that you want to appear on screen.
gets() By passing character array as parameter can. accept string input including spaces.
puts() By passing character array as parameter can display the content of string


Formatted functions
printf(char *,var,var... )
prints the formatted output on screen as specified in format specifier. same function can be used for displaying all the datatype variables.
eg. printf("i=%d, f=%f",i,f);
scanf(char *,var,var...)
Accepts the formatted input from user as specified in format specifier & in variable address given as parameter.
eg. scanf("%d",&i);

Example on all thses topics.

main()
{
int x=20;
char ch='A';
float f = 3.14;
double d = 3400.233;
printf("\nx = %d", x);
printf("\nx = %c", ch);
printf("\nx = %f", f);
printf("\nx = %lf", d);
printf("\nPress any key to continue");
getch();
}
A. Sequence : The normal sequence of program is from left to right and from top to bottom.
B. Selection : Selection construct allows programmer to write a program which is selectively executed, which means if the condition is satisfied one part of the program will be executed otherwise some other part will be executed. It is also called branching
In ‘C’ there are two selection constructs if... else & switch … case
C. Iteration : Iteration construct allows programmer to write a program with some statements, which repetetively execute some statements again and again. It is also called looping
In ‘C’ there are three iteration constructs : for, while & do …. while.
________________________________________
Selection Constructs
if... else example
main()
{
int i;
printf("\nEnter a number : ");
scanf("%d",&i);
if( I > 7 )
printf("I is greater than seven");
else
printf("I is not greater than seven");
}
swith… case example


main()
{
char grade;
printf("Enter your grade : ");
grade=getche();
switch(grade)
{
case ‘a’ : printf(" A grade gets Rs.700 Bonus ");
break;
case ‘b’: printf(" B grade gets Rs. 600 Bonus");
break;
case ‘c’: printf("C grade gets Rs. 500 Bonus");
break;
default : printf("Other than these grades gets Rs. 200 Bonus");
}
Iteration Constructs
for loop
when you know how many times the loop is to be executed, make use of for loop.

main()
{
int i;
for(i=0;i<10;I++) { printf("\n%d",I); } } while loop when you don’t know how many times the loop is to be executed, make use of while loop. main() { char ch=’ ’; while( ch !=’n’) { printf("\nAre you intelligent :"); ch=getche(); } printf("\nI am more intelligent than you"); } do… while loop when you want to execute the loop at least once even if the condition is false, make use of while loop. main() { int var=5; do { printf("\n var=%d",var); var++; }while(var > 10);
}
in above example even if the while condition is false at least once the loop is executed. So you get the output var=5;


break statement :
break statement breaks the loop, jumps out of the loop & rest of the code is executed normally.

main()
{
int i;
for(I=1;i<10;i++) { printf("\ni=%d",i); if(i==5) break; } printf("\nLoop ends here…"); } This program uses the loop which should display numbers from 1 to 10, but in between if statement checks for number equals to 5 & if it is found breaks the loop. But other code is executed normally. so it also displays the message Loop ends here… exit() where break breaks the loop, exit() statement terminates the program. If you want to terminate the program abnormally in between only it can be done by putting exit statement. After exit nothing is executed. Main() { int i; for(i=1;i<10;i++) { printf("\ni=%d",i); if(i==5) exit(); } printf("\nLoop ends here…"); } continue statement: continue statement can be given only in loops, after the continue statement nothing is executed, the control is passed back to beginning of loop with a next counter. main() { int var; for(var=1;var<=100;var++) { if(var%7==0) { printf(" * \t "); continue; } printf(" %d \t",var); } } this program displays the numbers from 1 to 100 and if the number is divisible with 7 it displays * and continues the work i.e. not printing the number and continuing the loop with the next counter. Operators Operators can be classified in different ways. This is the simplest way of understanding them. In expression ( A + B ) : + is operator & A & B are operands. Mathmetical Relational Logical Unary Binary Ternary + + ? & : > && ( And)
- - >= || ( Or)
++
(increment) * < ! ( Not ) -- (decrement) / <= % == != Using Simple Mathematical Operators main() { int x=20; int y=30; printf("x = %d, y = %d",x,y); printf("Addition : %d",(x+y)); printf("Subtraction :%d",(x-y)); printf("Division :%d",(x/y)); printf("Multiplication : %d",(x+y)); } Above example describes how to make use of Binary Operators. Simple operations like addition, subtraction, division, multiplication are demonstrated in this. Using Increment and decrement operator main() { int x=20; int y=30; printf("x = %d, y = %d",x,y); x++; y--; printf("x = %d, y = %d",x,y); } Above example shows increment and decrement unary operators. Where : x++ is nothing but x = x + 1 & x-- is nothing but x = x - 1 Using Ternary operator main() { int x=20; int y=30; int max = ( x > y ) ? x : y;
printf("x = %d, y = %d",x,y);
printf("max = %d ",max);
}
Ternary operator is used to put some comparision test. If true assign some value if false assign other.
(Condition) ? true : false;
syntax :
return type name(datatype variable, datatype variable,….);
functions are set of instructions combined together and given the name & can be used whenever you want by making a call to that function. There are two types of functions : User defined functions & Library functions. Both printf and scanf are examples of functions, Other functions supplied by the system in what are called libraries.
A function without any arguments

main()
{
display();
}
display()
{
printf("Syspro");
}
This program makes a call to ‘display’ function which prints Syspro on screen. Its is necessary that the function to which the call is made should be defined in the same file.


Passing the arguments to function :
while passing the arguments it is important to define datatype of the argument. By default C considers that the passed value is of integer type.

main()
{
sqr(8);
}
sqr(int val)
{
printf("squre of %d is %d", val, val*val);
}


The above program makes a call to sqr function which calculates the squre of the number, as well as displays the square of the number.
As per the programming rules any function should be cohesive which means it should solve only one purpose, it should not display the square of the number passed. Just calculate the square and return it.
Returning the value from the function
This program makes a call to sqr function which only calculates the square and returns calculated value which is stored in x variable.

main()
{
int x;
x=sqr(8);
printf("\nsqure of 8 is %d", x);
}
sqr(int val)
{
return(val*val);
}


Passing & returning different datatypes.
This program makes a calls to function
float area_of_circle( float );
main()
{
float area;
area=area_of_circle(2.4);
printf("Area of circle is %f",area);
}
area_of_circle(float radius)
{
return(3.14*radius*radius);
}
Scope of Variable
Variables can be of two types one local, another global, depending upon place of declaration scope of variable changes. Variable declared within a function is treated as local variable. Variable declared before main function is treated as global variable. Local variable is accessible locally to that function and not outside that function, but global variables can be accessed anywhere in the program.

main()
{
int loc=30;
printf("\n loc = %d",loc);
callfunc();
}
callfunc()
{
printf("\n loc = %d",loc);
/* this statement will give the error message undefined symbol loc */
}
Above program will give an error message in callfunc() function since the variable loc is defined in main function and is not available for callfunc() function. The same variable can be made available by making it of global type.

int g;
main()
{
g=34;
printf("Value of g is %d",g);
showg();
}
showg()
{
printf("Value of g is %d",g);
}


int g;
This program will show the g variable since it is of global variable. A global variable can be declared by defining it above the main function.
Call by Value
Prameters passed to function are transfered through call by value method. Which means though we transfer the variables to function but it takes value only from them. Actual variables are not getting affected.

main()
{
int x=20,y=30;
printf("\n In main Function x = %d, y=%d",x,y);
swap(x,y);
printf("\n In main Function x = %d, y=%d",x,y);
}
swap(int x,int y)
{
int t;
t=x;
x=y;
y=t;
printf("\n In swap Function x = %d, y=%d",x,y);
}
This program shows that variables defined in main function when passed to swap function swaps the contents but as soon as you return to main function they values you find are intact.

Here swap function is having its own local variables with the same name as x and y. These variables are modified by swaping but actual x and y variable remain intact as they were since variables are never passed to function only values of variables are transfered.
Single Dimension Array
An array is a group of elements that share a common name, and that are differntiated from one another by their positions within the array. For example, if we have five numbers, all which are named x, they may be listed.
x
58
64
23
09
87

The position of each of these elements can be indicated by means of subscript :
x1 = 58
x2 = 64
x3 = 23
x4 = 09
x5 = 87
subscript indicates the position of particular element with respect to the rest of the elements.
In C array is declared like :
int x[5];

Assignment statements can be written like
x[0]=58
x[1]=64
x[2]=23
x[3]=09
x[4]=87

There is no element x[5]. The reason for this unusual numbering scheme is that C was designed to model the operation of the computer at a level lower than dealt with by most programming languages. The calculation of the address corresponding to a subscript is simpler when the first array element is numbered 0.

main()
{
int x[5];
int ctr,sum;
for(ctr=0;ctr<5;ctr++)
{
printf("\n Enter the value : ");
scanf("%d",&x[ctr]);
}
for(ctr=0;ctr<5;ctr++)
{
printf("\n %d ",x[ctr]);
sum = sum + x[ctr];
}
printf("Sum of all elements is %d",sum);
}

array can be initialised at the time of declaration also.
Int arr[5] = { 3 , 4 , 5 , 7, 4 };


Character strings are the example of arrays itself.

main()
{
char str[30]="Syspro International";
int x;
for(x=0;str[x]!=’\0’;x++)
{
printf("\n%c",str[x]);
}
}

Double dimension arrays.
Double dimension arrays are having counter which not only increments by row but by column also, logically they can be represented in the following format.
Int arr[3][4];

12 34 4 54
23 45 3 45
32 56 76 56
The syntax for assignment of double dimension array is in following format.
arr[0][0]=12;
arr[0][1]=34;
the same can be done at the time of declaration also.

main()
{
int arr[3][4]={ {12,34,4,54},
{23,45,3,45},
{32,56,76,56}
};
int r,c;
for(r=0;r<3;r++)
{
for(c=0;c<4;c++)
{
printf("%d\t",arr[r][c]);
}
printf("\n");
}
}

There can be even Multi-Dimension Arrays.
Strings can be manipulated through following functions which are defined in the library STRING.H

strcpy() used to copy one string to another
strcmp() used for comparing two strings
stricmp() compares the strings by ignoring the case.
strlen() returns the length of the string
strcat() Concatenates the strings to another string
strrev() Reverses the string and returns the pointer of that
program to create two strings and assign concatenated form to third string.

main()
{
char str1[20]="Syspro",str2[20]=" Internationals";
char str3[40];
printf("\nFirst string contains %s",str1);
printf("\nSecond string contains %s",str2);
strcpy(str3,str1); /* copy string 1 to string 3 */
strcat(str3,str2); /* concatenate string 2 to string 3*/
printf("\n After copy and concatenating string 3 contains %s",str3);
}
following program calculates the length of string.

main()
{
char name[20];
int l;
printf("Enter your name :");
scanf("%s",name);
l=strlen(name);
printf("The length of the %s string is %d",name,l);
}
program to see the entered string is palindrome or not.

main()
{
char str1[20],str2[20];
printf("Enter the word : ");
scanf("%s",str1);
strcpy(str2,str1);
if( strcmp(str1,str2)==0)
printf("Entered word is palindrome");
else
printf("\nEntered word is not palindrome");
}
Examples of Palindromes are like MADAM, MALYALAM, where reversing the string does not changes the meaning of word.
Pointer is a memory variable that holds the address of another variable, which is called pointing to variable. Using the pointer variable the contents of the variable to which it is pointing can be accessed directly & also can be changed. Pointers are declared using the ‘*’ as prefix operator.
Int *ptr;
the address of other variables can be assigned using ‘&’ prefix operator.
int i=30;
ptr=&i;

Here is the program to explain the same.

main()
{
int x=30;
int *ptr;
ptr=&x;
printf("\n x=%d",x);
printf("\n &x=%u",&x);
printf("\n ptr=%u",ptr);
printf("\n *ptr=%d",*ptr);
}
values of the variable can be modified to which the pointer is pointing.

main()
{
int x=30;
int *ptrx=&x;
printf("\n before assignment x = %d",x);
*ptrx=20;
printf("\n After assignment x = %d",x);
}
The datatype of the pointer is not to specify the type of data pointer will be storing but to specify to what datatype it will point in future. All the pointer variables are of unsigned int type.

main()
{
int *iptr;
float *fptr;
char *cptr;
printf("\nSize of integer pointer is %d",sizeof(iptr));
printf("\n Size of float pointer is %d",sizeof(fptr));
printf("\n Size of char pointer is %d",sizeof(cptr));
}
The above program shows though the pointers are of different types, still all of them occupy the same space in memory i.e. 2 bytes. This proves that datatype of pointer is not to decide what pointer is storing but to what it is pointing.
Call by reference
While we were learning User Defined functions we have done an example on call by value, Here comes a method Call by Reference which is related to that topic.
main()
{
int x=20,y=30;
printf("\n In main Function x = %d, y=%d",x,y);
swap(&x,&y);
printf("\n In main Function x = %d, y=%d",x,y);
}
swap(int *x,int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
printf("\n In swap Function x = %d, y=%d",*x,*y);
}
Here in this example instead of passing values of variables we are passing the addresses of variables and they are stored in pointer variables in function swap. Swap function uses these address and modifies the contents of variables to which its pointing. So through pointers we can change the contents of variables for swap purpose.

Other Topics that can be done with pointers are like
( To maintain the syllabus concise & Simple these topics are not explained here).
• Pointers and Arrays.
• Pointer to pointer
• Dynamic Memory Allocation
• Direct Access to MS-DOS memory location
If all the data elements of a program are of the same type, they can be represented as an arrya. If the elements are of different types, however, the array is inadequate to the task. We resort to an entity known in C as structures.
One employees information can be stored in different variables in following fashion.
int empno;
char name[20];
float sal;

This can be grouped together in structure and can be stored as single entity.

struct empinfo {
int empno;
char name[20];
float sal;
};
A structure defination is specified by the keyword struct. This is followed by templete, surrounded by braces, which describes the members of the structure. A member of a strucutre is a single unit, so the structure shown here has three members.

A program to accept structure data information and display the same can be like this.

struct empinfo {
int empno;
char name[20];
float sal;
};
main()
{
struct empinfo data;
printf("\nEnter the emp no : ");
scanf("%d",&data.empno);
printf("\nEnter the name : ");
scanf("%s",data.name);
printf("\nEnter the salary :");
scanf("%f",&data.sal);
printf("\nemp no : ",data.empno);
printf("\nname : ",data.name);
printf("\nsalary :",data.sal);
}
Each member of structure variable is specified by following the variable name with a period and the member name. The period is the structure member operator.

Assigning the structure values at the time of declaration only.

main()
{
struct empinfo data={23,"Deepak",2300.50);

printf("\nemp no : ",data.empno);
printf("\nname : ",data.name);
printf("\nsalary :",data.sal);
}