c_(2)

29
Introduction: A language is a mode of communication between two people. It is necessary for those two people to understand the language in order to communicate .But even if the two people do not understand the same language; a translator can help to convert one language to the other. Similarly we need a language to communicate with the computer .A translator is also needed to convert from users form to computer form. Like other languages, a computer language also follows a particular grammar known as syntax. 1 Objectives : After going through this unit you will be able to: -define what a program is? -understand what a C programming language is? -compile a C program, identify the errors and run a C program -understand the main components of a C program 1.1What is a program and a programming language? To do any work with the computer we have to give some instructions .That set of instructions arranged in a logical sequence is called as a program. In practice it is necessary to express a program using programming language .A procedure expressed in a programming language is known as a computer program. Programming languages can be divided into two categories 1.2 low level or machine level languages: The language whose design is governed by the circuitry and the structure of machine is known as machine language. This language is difficult to learn and use. It is specific to a given computer and is different for different computers i.e these languages are machine dependent. These languages have been designed to give a better

Upload: veeresh-khelgi

Post on 24-Dec-2015

1 views

Category:

Documents


0 download

DESCRIPTION

documeny

TRANSCRIPT

Introduction:

A language is a mode of communication between two people. It is necessary for those two people to understand the language in order to communicate .But even if the two people do not understand the same language; a translator can help to convert one language to the other. Similarly we need a language to communicate with the computer .A translator is also needed to convert from users form to computer form. Like other languages, a computer language also follows a particular grammar known as syntax.

1 Objectives:

After going through this unit you will be able to:

-define what a program is?

-understand what a C programming language is?

-compile a C program, identify the errors and run a C program

-understand the main components of a C program

1.1What is a program and a programming language?

To do any work with the computer we have to give some instructions .That set of instructions arranged in a logical sequence is called as a program. In practice it is necessary to express a program using programming language .A procedure expressed in a programming language is known as a computer program.

Programming languages can be divided into two categories

1.2 low level or machine level languages:

The language whose design is governed by the circuitry and the structure of machine is known as machine language. This language is difficult to learn and use. It is specific to a given computer and is different for different computers i.e these languages are machine dependent. These languages have been designed to give a better efficiency ,i.e faster program execution such languages are also known as low level languages. Another type of language is assembly language .we code the assembly language program in the form of mnemonics. Every machine provides a different set of mnemonics to be used for that machine only depending upon the processor that the machine is using.

1.2.2 high level language or problem oriented languages:

These languages have been designed to give a better programming efficiency, i.e faster program development. Every high level language follows a precise set of rules They are developed to allow application programs to be run on a variety of computers. These languages are FORTRAN, BASIC, and PASCAL etc. They are easy to learn and programs may be written in these languages with much less effort. However, the computer cannot understand them and they need to be translated into machine language with the help of other programs known as compilers or translators.

C LANGUAGE:

Before writing C program, we will find out what really is C language, how it came into existence and where does it stand with respect to other computer language. We will briefly outline these issues in the following section.

1.3.1 HISTORY OF C:

C is a programming language developed at AT&T’s bell laboratories of USA in 1972. It was designed and written by a man named DENNISRITCHIE. In the late seventies c began to replace the more familiar languages of that time like PL\I, ALGOL etc.

By 1960,many programming languages came into existence, almost each for a specific purpose for example COBOL was being used for commercial or business applications, FORTRAN for scientific applications and so on .so, people started thinking why could not there be a one general purpose language .Therefore ,an international committee was set up to develop such a language ,which came out with the invention of ALGOL60,but this language never became popular because it was too abstract and too general. To improve this, new language called combined programming language (CPL) was developed at Cambridge University. But this language was very complex in the sense that it has too many features and it was very difficult to learn. Matrin Richards at Cambridge University reduced the features of CPL and developed a new language (BCPL). But unfortunately it turned out to be much less powerful and too specific. Ken Thompson at AT & T’s bell labs, developed a language called B, but like BCPL this was also too specific. Ritchie inherited the features of B and BCPL and added some features on his own and developed a language called C. C proved to be quite compact and coherent.

1.3.2 Features of C:

1.3.2.1 Middle Level Language: Among the two types of programming languages discussed earlier, C lies in between these two categories. That’s why it is often called a middle level language, since it was designed to have both: relatively good programming efficiency and relatively good machine efficiency.

1.3.2.2 Portability: C code is very portable, that it allows the same C program to be run on the machines with different hardware configurations.

1.3.2.3 Flexibility: The flexibility of C allows it to be used for systems programming as well as for application programming.

1.3.2.4 Structure Language: C is commonly called a structured language because of structural similarities of ALGOL and PASCAL. Structured language is one that divides the entire program into the modules using top-down approach where each module executes one job or task.

It is easy for debugging, testing and maintenance if a language is structured one.

Check your progress

1.”a program written in low level language is faster “.why?

2.what is difference between high level language and low level language?

3.why c is referred to as middle levl language?

1.4 structure of a c program:

To solve a problem there are three main things to be considered .firstly what should be the output?

Secondly what should be the input that will be required to produce this output and thirdly the steps of instructions which use these inputs to produce the required output .every programming language follows a set of rules known as syntax . C is a case sensitive language. All c programs consist of one or more functions .one function that must be present in every C program is main(). This is the first function called up when the program execution begins.Basically main() outlines what a program does.

The structure of a c program is illustrated in below figure. Where functions fun1() , fun2() represent user defined functions.

1.4.1 A simple program:

From the above section you have become familiar with a programming language and structure of a program .It is now time to write a simple C program .The program will illustrate how to print out the message “this is a C program”.

Example 1.1: write a program to print to a message on the screen

Preprocessor directives

Global data declarations

main() /* main function */

{

Declaration part ;

Program statements;

}

/* user defined functions */

fun1()

{

-------

-------

}

fun2()

{

------

}

/*program to print a message*/

#include<stdio.h> /*header file*/

main () /* main function* { printf(“This is a program”); /*output statement*/ } Though the program is very simple, a few points must be noted. Every C program contains a function called main (). This is the starting point of the program. This is the point from where the execution begins. It will usually call other function to help perform its job, some that we write and others from the standard libraries provided.

#include<stdio.h> is a reference to a special file called stdio.h which contains information that must be included in the program when it is compiled. The inclusion of this required information will be handled automatically by the compiler. You will fine it at the beginning of almost every C program. Basically all the statements starting with ‘# ‘ in C program are called preprocessor directives .these will be considered in the later units just remember that this statement allows you to use some predefined functions such as printf() In this case

main() declares the start of the function while the two curly{ } shows the start and finish of the function. curly brackets in C are used to group statements together as a function or in the body of a loop .such a grouping is known as a compound statement or a block every statement within a function ends with a terminator semicolon(;).

printf(“this is a C program”); prints the words on the screen .The text to be printed is enclosed in double quotes.Comments may appear any where within a program as long as they are placed with in the delimiters /* and*/ such comments are helpful in identifying the program principal features or in explaining the underlying logic of various program features.

1.4.2 compiling a C program:

After writing the program the next step is to save the program in a file with extension .c .This program is in high level language but the language is not understood by the computer. So the next step is to convert high level language to machine language. T his task is performed by the software or program known as compiler .Every language has its own compiler that converts source code to object code.The compiler will compile the program successfully if the program is syntactically correct.If the program contains syntax errors they will be displayed on the screen and the object file will not be produced .The errors need to be removed before compiling the program.This process of removing the errors from the program is called as debugging.C follows certain syntax rules. When a C program is compiled ,the compiler will check that the program is syntactically correct. If there are any syntax errors in the program, those will be displayed on the screen with the corresponding line numbers.

Check your progress

1. What is the basic unit of a C program?2. What is the use of compilers?3. Indentify syntax errors in the following programcode:

#include<stdio.h>main(){Printf(“hai”);}

1.4.3. Link and Run the c program:

After compilation, the next step is linking the program. Compilation produces a file with an extension .obj. Now this .obj file cannot be executed since it contains calls to function defined in the standard library of C language. These functions have to be linked with the code you wrote ,C remembers it’s name . Later the linker combines the code you wrote with the object code already found in the standard library . This process is called linking. In other words linker is a program that links separately compiled functions together into one program. It combines the functions in the standard C library with the code that you wrote. The out put of the linker is an executable program . i.e, a file with an extension .exe.

1.5 character set, identifiers and keywords:

As every natural languages has a basic character set,computer languages also have a character set,rules to define words. Words are used to form statements ,these in turn are used to write the programs.

The basic elements used to construct simple C program statements are C character set,identifiers , keywords, datatypes, constants, variables,declaration and naming conventions of variables.

1.5.1 character set:

A character denotes any alphabet,digit or special symbol used to represent information. following table shows the valid alphabets numbers and special symbols allowed in C:

Alphabets A,….Z, a….z

Digits 0,1,2,3,4,5,6,7,8,9

Special symbols ~’!@#$%^&*()_+|<>{}[]:;”’?

1.5.2 identifiers:

Identifiers refer to the names of variables, functions and array. These are user_defined names and consists of a sequence of letters and digits , with a letter as a first character. both upper case and lower cases letters are permitted, although lowercase letters are commonly used. The underscore character is also permitted.

Rules for identifiers:

1.First character must be an alphabet

2.Must consists of only letters,digits or underscore

3.Only first 31 characters are significant

4. Cannot use a keyword

5. Must not contain white space.

Variable:

A variable is an identifier for a memory location in which data can be stored and subsequently recalled.

1.5.3 keywords:

Keywords are reserved words which have standard ,predefined meaning in C. keywords serve as basic building blocks for program statements. They cannot be used as program_defined.identifiers

The list of C keywords are as follows:

Char while do typedef autoInt if else switch casePrintf double struct break staticLong enum register extern returnUnion const float short unsignedContinue for signed void defaultGoto sizeof volatile

Data types of C:

The data type of a variable determines a set of values that a variable might take and a set of expressions that can be applied to those values. Data types can be broadly classified as

1.Primary data types

2.Derived data types

3.User defined data types.

Primary data types:

These are also called basic data types or fundamental data types.

All C compilers support five fundamental data types.

Data type keyword

1.integer int

2.floating point float

3.double precesion double

4.character char

5.void void

NOTE: C99 support three more data types, namely bool, complex, imaginary

These data types can have the

1. size qualifier eg: short ,long and long long

2. sign qualifier eg: signed and unsigned

Integer data type:

Integers are whole numbers with a range of values supported by a particular machine. If a system allocates 16 bits, to an integer, one size of integer value is limited to one range 32,768 to 32,767

(i.e-215 to 215-1).

In order to provide some control over the range of numbers and storage space, C has four classes of integer storage, namely short int, long int, and long long int, in both signed and the unsigned forms.

Size and range of values of integer data types for 16 bit machine

Data type Size(bits) Range Default type

Int 16 -215 to 215-1 signed int

Unsigned int 16 0 to 216-1 unsigned

Signed int 16 -215 to 215-1 int

Short int 16 -215 to 215-1 short

Unsigned short int 16 0 to 216-1 unsigned short

Signed short int 16 -215 to 215-1 short, signed short, short Int

Long int 32 -231 to 231-1 long ,signed long ,signed long int

Unsigned long int 32 0 to 232-1 unsigned long

Signed long int 32 -231 to 231-1 long int, long, signed long

Declaration of integer variables will be as follows :

int l, m;

short a, b; same as short int a,b;

long int p; same as long p;

unsigned int x; same as unsigned x;

Floating point types:

Floating point numbers are stored in 32 bits (on all 16 bit machines),with 7 digit precision .Floating point numbers are defined by the keyword float .When the accuracy provided by a float number is not sufficient , the type double can be used to define the number . A double data type number uses 64 bits giving a precision of 15 significant digits .to extend the precision we may use long doube which uses 80 bits.

Size and range values of floating data types on 16 bit machine.

Data type Size(bits) Range Precision

Float 32 3.4e-38 to 3.4e38 7 digits

Double 64 1.7e-308 to 1.7e 308 15 digits

Long double 80 3.4e-4931 to 1.1e4932 20 digits

Floating point variables declaration are as follows:

float a,b;

long float l,m;

double p,q;

long double x,y;

Character types:

A single character can be defined as a character type of data. Characters are stored on 8 bits of space. The qualifier signed or unsigned may be applied to char .signed char have values between -128 to 127 and unsigned char have values between 0 to 255.

Character type variable declaration is as follows:

char ch;

Void type:

The void type has no value. This is usually used to specify the type of function , that does not return any value to the calling function.

Eg: void main()

Complex types:

The variables of complex types can be declared by the type specifiers float complex, complex, or double complex , and long double complex. The type specifier complex and the macro I for representing imaginary part and defined in the header file complex.h. the size of complex number of type float complex is 8 bytes and double complex is 16 bytes.

Eg:

float complex z1;

double complex z2;

complex z3;

z1=2+i3

Boolean type:

This data type is represented by the keywprd bool defined in stdbool.h thi s data type is used for relational comparisons logical operational. Boolean variable can take two values :1 for true and 0 for false , are defined in stdio.h

Eg:

bool b;

B=1;

B=x>y;

Pointer type:

A variable of pointer type can be declared similar to variables of other data types. At declaration pointer type can be distinguished by an asterisk ‘*’ preceding the variable name

Eg:

int x,*p;

float y,*q;

p=&x; q=&y;

A pointer can be printed out using the function printf() with the format specifier “%p”.

Eg: printf(“the values of p is %p\n”p);

Operators and Expressions:

C supports a rich set of built in operators. C Operators can be classified into the following categories.

1. Arithmetic operators2. Relational operators3. Logical operators4. Assignment operators5. Increment and Decrement operators6. Conditional operators (Ternary operator)7. Bitwise operator8. Special operator

Expression: Variables and constants connected by operator is called expression.

1. Arithmetic operators: Arithmetic operations involve negation, addition, subtraction, multiplication and division as shown in the following table.

Operator Operation Description

- -x negation

+ +x unary plus

+ x + y addition

- x – y subtraction

* x * y multiplication

/ x / y division % x % y modulus

The expression i % j would result in the remainder of i divided by j.Eg: int i= 10, j=3, k;k=i%j; 1 is assigned to the variable k.

The modulus operator can be used only with integer operands.Eg: float x, y, z;z=x % y; is not valid.

All other operators can be applied to operands of the arithmetic type, which consists of integer, floating point or complex types.

When both the operands in an expression are integers, the expression is called integer expression. Integer arithmetic leads an integer value.Eg: 25/7=3, 3/4=0, 4/3=1

When both operands are floating point type the expression is called floating point type expression.Eg: x=5.2, y=1.42;z=x/y;

When one of the operand is real and the other is integer the expression is called a mixed mode expression. The result is floating point type value.Eg: 23/5.0=4.6

Type conversion in expression:

1. Implicit type conversion.2. Explicit type conversion.

Implicit type conversion:

C permits mixing of constants and variables of different types. A data type that occupies less memory can be converted automatically to a data type that occupies more memory space without losing any information.

Eg: If one operand is int and the other is float, int is converted to float. If one operand is double and the other is long double, double is converted to long double. If a char and double are combined, char is converted to double.

The hierarchy of type conversion is summarized in the following table:

Data type Order

Long double complex

Double complex

Float complex high

Long double

Double

Float

Unsigned long long

Long long

Unsigned long

Long

Unsigned int low

Int

unsigned short int

short int

Unsigned char

Char

Explicit type conversion:

For explicit type conversion type casting is used.

The general form of a cast is:

(data type-name) expression

Where type name is one of the basic data types.

Example Action

x= (int) 3.7 3.7 is converted to integer by truncation

x= (int) 13.7/ (int) 4.3 Evaluated as 13/4 and the result would be 3

x= (float) (a + b) the result of a + b is converted to float

p= cos( (double) x) converts x to double before using it.

Relational Operators:

Relational Operators are used to compare the values of two expressions. An expression such as

a < b, n! =0, p>q

Containing a relational operator is termed as a relational expression .The value of a relational expression is either one or zero. It is one if the specified relation is true and zero if the relation is false.

For example,

int i=5,j=3,k;

k= (i<j); 0 is assigned to k

k= (i==j); 0 is assigned to k

k= (i>=j); 1 is assigned to k

Relational Operators

Operator Operation Description

< x < y less than comparison< = x < = y lesser or equal comparison = = x = = y equal comparison >= x >= y grater or equal comparison

> x > y greater comparison!= x != y not equal comparison

Logical Operators

There are three logical operators

Operator Operation Description

! ! x logical negative operation

&& x && y logical AND operation

|| x || y logical OR operationIf the operand of the Unary logical negative operator! Is nonzero, the result is true otherwise, the

result is false

Ex:

!0=1

!3.7=0

! (-20)=0

Consider the expression

exp1||exp2

If exp1 is true then exp2 is not valuated.

Ex: result always true

int i=6,j=3,k;

K=(i>5)||(j!=3);

printf(“k=%d ,n”,,k);

output: k=1

Ex: i=6,j=3,k;

k=(i<5)||(j=5+10);

printf(“k=%d,j=%d”,k,j);

output : k=1,j=13

Increment and decrement operators(++ and--): These two operators are unary operators. They exists in two forms i.e. pre and post

Increment operator(++):

Increment operator is used to increment the value of its operand by 1.general form for pre incrimination is ++ operand and post incrimination is operand++. where the operand must be a variable but can’t be a expression.

In the above example prefix and postfix operation results in the same output. the prefix and postfix operations differ in the value used for the operand when it is embedded inside expressions

Eg3:

int x=10,y;

Y=++x;

Printf(“x=%d,y=%d”,x,y);

Output:

x=11,y=11

Here x value is incremented before it is assigned to y so the statement y = ++x is equivalent to the two statements x=x+1 and y=x

Eg1: pre incrementation

int i=20;

++i;

Printf(“i=%d/n”,i);

Output:

i=21

Eg2: post incrementation

int i=20;

i++;

Printf(“i=%d/n”,i);

Output:

i=21

Eg4:

int a=5,b;

b=++a*4;

Printf(“a=%d,b=%d”,a,b)

Output:

a=6,b=24

Post increment:

Eg5:

int x=10,y;

y=x++;

Printf(“x=%d,y=%d”);

Output:

x=11,y=10

Here value of x is incremented after it is assigned to y, thus the statement y=x++ is equivalent to the statements y=x and x=x+1;

Eg6:

int a=5,b;

b=a++*4;

Printf(“a=%d,b=%d”);

Output:

a=6,b=20

++4 or ++(x+y) are invalid expressions.

Decrement operator ( - - ):

This operator is used to decrement the value of the operand by 1.General form is operand-- or

--operand.where the operand must be a variable but cannot be constant or expression.--operand is called pre decrement or prefix decrement and operand-- is called post decrement or postfix decrement

Eg1: int i=10; Eg2: int i=10;

--i; i--;

Printf(“i=%d”,i ) ; Printf(“i=%d”,i);

Output: i=9 output: i=9

In the above example both the prefix and postfix operations results in the same value.

Eg3:

Prefix decrement:

int a=10,b;

b= -- a*3;

Printf(“a=%d,b=%d\n”,a,b);

Output:

a=9,b=27

Eg4:

Post decrement:

int a=10,b;

b=a--*3;

Printf(“a=%d,b=%d\n”,a,b);

Output:

a=9,b=30

5. Assignment Operators: There are three forms of assignment: simple assignment, multiple assignment and compound (short hand) assignment.

Simple assignment: The operator used is ‘=’.

The general form is

Variable name = expression ;

The value of the expression is evaluated first and is assigned to the variable. The evaluation of the expression is right to left.

Eg: x=10 a=10 && 5 y=12.5 a=x>y a=”A” area=0.5*b*h.= is the assignment operator used to assign right side expression value to the left hand side variable.= = is comparison operator to compare the value of left hand and right hand side expression.a=b will assign b value to a a==b will compare the values of a and b for equality.

Multiple assignment: This is used to assign the value of an expression to two or more variables.

The general form is

v1=v2=v3=expression;

The value of the expression is assigned to the variables v1, v2, v3 etc. the evaluation is right to left.Eg: a=b=0. a=b=x+y The value of x+y is assigned to b and then the value of b is assigned to a.

Compound assignment: Compound assignment is a short hand notation for a simple assignment.The compound assignment operators are+ =, - =, * =, / =, % =.To evaluate a compound assignment expression, first change it to a simple expression.

Compound assignment Equivalent simple expression

x+=expression x=x+expression x-=expression x=x-expression x*=expression x=x*expression x/=expression x=x/expression x%=expression x=x%expression

a*=b+3 is evaluated as a=a*(b+3)sum+=x is evaluated as sum=sum+xa%=10 is evaluated as a=a%10.

6. Conditional operator (? :)

The conditional operator has three expressions.

The general form is

expression1? expression2: expression3

This is called conditional expression.

First expression1 is evaluated. If the result us non-zero, the expression2 is evaluated and its value is the final result. Otherwise, expression3 is evaluated and its value is the final result.

Eg1: To find the biggest of two numbers big= (a>b)? a: b;

This is equivalent to the if –else statement if (a>b) big=a; else big=b;

Eg2: To check an integer is even or odd (n%2)? printf (“Given integer is odd\n”): printf(“Given integer is even\n”);

This is equivalent to the statement

if(x%2)

Printf(“given integer is odd\x”);

else

Printf(“given integer is even\x”);

Eg3:to find absolute value of an expression

y=(x>=0)? x: -x;

Eg4:

To evaluate the function defined by

F(x)= x^2-x+1 of x>=0

x^2+x+1 of x<0

f(x)=x>=0)?(x*x-x+1):(x*x+x+1);

conditionalexpression may be nested

Eg5:to find the biggest of the numbers

big=(a>b)?((a>c)?a:c):((b>c)?b:c);

although conditional expression is nested,it is not recommended.

7.special operators:

Comma operator(,) , sizeof operator , address operator(&),

indirect operator(*),and cast operator are called special operators.

Comma operator:

The comma operator is used to combine two more expressions into a single expression.

The general form is

expression1;expression2,----------expressionN.

Where the expression are evaluated from left to right and the value of the last expression is the result of the overall expression.

Eg1:

int i=10,j;

j= ( i+=5, --i , i+20);

j is assigned the value 34.

Eg2: int m=5,n;

n=(m+=5,m%3);

n is assigned the value1.

Eg3: swapping of two integer variable using the comma operator

temp=a , a=b , b=temp;

The comma operator is most often used in for statement expressions.

Eg4: for(i=1 , j=10 ; i<j ; ++i , --j)

{

Statements;

}

Sizeof operator: This operator is used to determine the number of bytes required to store a particular datatype item in the memory .

General form is

sizeof(operand)

Eg1:

printf(“char size is %d bytes\n” , sizeof (char));

Printf(“longint size is %dbytes\n” , sizeof(double));

Printf(“doublesizeis %dbyte\n”,sizeof(double));

The operand of a size of operator can be a constant on variable or expression

Eg2:

sizeof(13.56),sizeof(239462l),

Sizeof(896254ll),sizeof(‘*’),sizeof(a+b)etc are valid.

Cast operators:These operators are used to convert the datatype of operand explicitly to another type.

The general form is

(datatype)expression

Where datatype is int,double,char or pointer etc.

Eg1:(int)9.3 ,(double)15,(float)327,3/(int)7.2,(int)8.5/(int)4.3

Eg2:int a=10,b=6;

float x;

x=(float)a / (float)b;

The value assigned to x is1.6666666

Precedence and Associativity of operators

Precedence is used to determine the order in which different operators in a complex expression are evaluated.

Associativity is used to determine the order in which operators with the same precedence are evaluated in a complex expression.

The precedence and associativity of different categories operators is presented in the following table:

Operators Associativity1 ( ),[ ], . , -> , ( ++ ) postfix, ( -- )postfix L to R2 ( ++ prefix), ( -- prefix), unary +, unary -,

& (address), *(indirection), cast, !(negation)R to L

3 *, /, % L to R4 +, - L to R5 <, <=, >, >= L to R6 = =, != L to R7 & & L to R8 | | L to R9 ? : R to L10 =, +=, *=, -=, /=, %= R to L11 , (comma operator) L to R

Eg1: 2+3*4 is evaluated as 2+(3*4) ->14

Eg2: 3*8/4%5*2

Here we have four operators of the same precedence (* / % *). As the associativity of arithmetic operators is left to right. The expression 3*8/4%5*2 is evaluated as

(((3*8)/4)%5)*2 ->2.

Eg3: a+=b*=c - =5

As the associativity of assignment operators is right to left, the above expression is evaluated as

(a +=(b*=(c - =5)))

Which is expanded to (a=a+(b=b*(c=c-5))).

Eg4: -b++

Here postfix increment has higher precedence than unary -. Thus the above expression is evaluated as

(-(b++)).

If b is 6, then the result of the expression is -6. After the expression is complete 6 becomes 7.