You are on page 1of 43

Intro to C

G.Sakthinathan DoME

INTRODUCTION TO C
C is a general purpose languages like Pascal, BASIC,

FORTRAN and COBOL.


C was evolved from ALGOL, BPCL and B by Dennis Ritchie at

Bell laboratories in 1972 .


C uses many concepts from these languages and added the

concepts of data types and other powerful features.


There is also various special purpose languages whose

instruction sets are specifically designed for some type of application.

The use of high level language offers three significant advantages

over the use of machine languages namely simplicity, uniformity and portability.
A program written in high level language must, however be

translated in to machine language before it can be executed. (Compilation).


A compiler or interpreter is itself a computer program that

accepts a high level program as input data, and generates a corresponding machine language program as output.
The original high level program is called a source program and

the resulting machine language program is called object program.

Desirable Program Characteristics

a) Integrity : This refers to the accuracy of the calculations. The integrity of the calculations is an absolute necessity in any computer program. b) Clarity: This refers to the overall readability of the program, with particular emphasis on its underlying logic. c) Simplicity: The clarity and accuracy of a program are usually enhanced by keeping things as simple as possible, consistent with the overall program objectives.

d) Efficiency This is concerned with execution sped and efficient memory utilization. e) Modularity Many programs can be broken down into a series of identifiable subtasks. It is good programming practice to implement each of these subtasks as a separate program module. In C, such subtasks are called as functions. f) Generality The program must be as general as possible, within reasonable

Preparing a Computer Program Study the requirement specification for the application. Analyze the problem and decide how to solve it. Translate the algorithm into a suitable high-level language. This written form of the program is often called the source program or source code. Compile the program into machine-language. The machine language program produced is called the object code. (At this stage the compiler may find Syntax errors in the program.)

The object code produced by the compiler will then be linked with various function libraries that are provided by the system. This takes place in a program called a linker and the linked object code is then loaded into memory by a program called a loader. Run the compiled, linked and loaded program with test data. Debug the program.

Algorithm
Definition of Algorithm A precise description of a step-bystep process that is guaranteed to terminate after a finite number of steps with a correct answer for every particular instance of an algorithmic problem that may occur.

Memory Concepts Variables Variable names correspond to locations in the computer's memory. Every variable has a name, a type, a size and a value. Whenever a new value is placed into a variable (through scanf, for example), it replaces (and destroys) the previous value. Reading variables from memory does not change them A visual representation integer 45

C PROGRAMS
C is one of the most popular computer languages, because it is a

structured, high-level machine independent language.


The popularity of C is probably due to its many desirable qualities. It

is robust language whose rich set of built-in functions and operators can be used to write any complex program.
There are only 32 keywords and its strength lies in built-in functions.

Several standard functions are available which can be used for developing programs.

A programming language is designed to help process certain

kind of data consisting of numbers, characters and strings and to provide useful output known as information.
The task of processing of data is accomplished by executing a

sequence of precise instruction called a program.


These instructions are formed using certain symbols according

to some rigid rules known as syntax rules.

Writing C Programs
The programmer uses a text editor to create or modify files

containing C code.
C code is also called source code A file containing source code is called a source file After a source file has been created, the programmer must

invoke the C compiler.

Using the C Compiler Invoking the compiler is system dependent. Two C compilers are available, cc and gcc. cc compiler is used often, because the error messages given by the cc compiler are easier for beginners to understand. Eg: cc pgm.c a program where pgm.c is the source file that contains

Stages of Compilation In the compilation process, there are three stages. (1) Preprocessor - modifies the source code - Handles preprocessor directives - Strips comments and white space from the code (2) Compiler - translates the modified source code into object code # Parser - checks for errors # Code Generator - makes the object code # Optimizer - may change the code to be more efficient

(3) Linker

- combines the object code of our program with other object code to produce the

executable file. The other object code can come from: an The Run-Time Library - a collection of object code with index so that the linker can find the appropriate code. other object files other libraries

Editor Source File pgm.c Compiler Preprocessor Parser Code Generator Optimizer Object File myprog.o Other Objs Run-time library Other libraries Linker Executable file a.out

Compilation Diagram

The Result : a.out If there are no errors in pgm.c, this command produces an executable file, one that can be run or executed. a.out To execute the program, type a.out at the Unix prompt. Both the cc and the gcc compilers name the executable file

Anatomy of a C Program program header comment preprocessor directives main ( ) { statement(s) }

Program Header Comment




All comments must begin with the characters /* and end with

the characters */
 The program header comment always comes first 

The program header comment should include the filename,

author, date written and a description of the program

Preprocessor Directive


Lines that begin with a # are called preprocessor

directives


The #include <stdio.h> directive causes the preprocessor

to include a copy of the standard input/output header file stdio.h at this point in the code.


This header file was included because it contains

information about the printf ( ) function thats used in this program.

main ( )
 Every program has a function called main, where

execution begins
 The parenthesis following main indicate to the compiler

that it is a function CHARACTER SET The characters that can be used to form words, numbers and expressions depend upon the computer on which the program is run. The characters in C are grouped into the following characters: Letters, Numerals, Special Characters ,White spaces

IDENTIFIERS AND KEYWORDS Identifiers are names given to various program element such as variable functions and arrays. Identifiers consists of letters and digits, in any order, except that the character must be the first letter. Both upper and lowercase letters are permitted. The underscore character (-) can also be included and is considered to be a letter. An identifiers can be arbitrarily long. C can recognize up to 31character

KEYWORDS
Keyw ord s 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

DATA TYPES C language is rich in data types. Storage representations and machine instructions to handle constants differ from machine to machine. C supports three classes of data types:
  

Primary (or fundamental) data types Derived data types User-defined data types

All C compilers support five fundamental data types namely integer (int), character (char), floating point (float), double precision floating point (double) and void. Many of them also offer extruded data types such as long int and long double.

DATATYPE int

DESCRIPTION integer quantity single character floating point number

MEMORY 2 bytes

RANGE -32,768 to 32767 0 to 65,535 (unsigned int) -128 to 127 0 to 255 (unsigned char) -3.4E -38 to 3.4E +38

Char

1 byte

float

4 bytes

double

doubleprecision

8 bytes

1.7e-308 to 1.7e +38

Integers (a) short shortint This may require less memory than an ordinary int or it may require the same amount of memory as an ordinary int. longint: This may require the same amount of memory as an ordinary int or it may require more memory but it will never be less than an ordinary int. (b) long (c) signed & unsigned.

signed & unsigned - An unsigned int has the same memory requirements as an ordinary int. - In the case of signed int the leftmost bit is reserved for the sign. - With an unsigned int all the bits are used to represent numerical value. Characters -The char type is represented in individual characters. -each character has an equivalent integer interpretation, so char is really a type of integer. Float A signed or unsigned number having decimal point.

Double A double-precision floating point number The difference between floating point and double precision numbers is the storage used by the computer for each type. Most computers use twice the amount of storage for double precision numbers than for floating point numbers. The sizeof operator can be used to determine the amount of storage reserved by the particular computer for each of these data types.

CONSTANTS: (NUMERIC CONSTANTS) Integer constants It can be written in three different forms Decimal(base 10):It consists of any combination of digits taken from the set 0 to 9. If the constant contains two or more digits , the first digit must be zero. Octal (base 8):It consists of combination of digits taken from the set 0 trough 7,however the first digit must be zero, in order to identify the constant as an octal number. Hexadecimal (base 16):It must begin with an 0x or 0X. It can be followed by any combination of digits taken from the set 0 through 9 and through alphabets a through f(either upper or lower case).

Floating point constants It is a base number that contains either a decimal point or an exponent. Eg. 0.006e-3 (NON-NUMERIC CONSTANTS) Character constants It is a single character and enclosed with apostrophes. Characters are ordered as well as enclosed. Digits are ordered consecutively in the proper numerical sequence 0 to 9 and the letters are arranged in the alphabetical manner with uppercase preceding lowercase. ASCII values : 48 57; A-Z 65 90 ; a-z 97 122;

String constant:
It consists of any number of consecutive characters enclosed in double quotations marks. The compiler automatically places the null character \0 at the end of the string so that a program scanning a string can find its end.  The physical storage is thus one byte more the number of characters enclosed within double.

Declarations A declaration associates a group of variables with a specific datatype. Eg: int a,b,c; float f,m;

char flag,rem;

Symbolic constants It is that substitutes a value for the characters. It may represent numeric constant, a numeric constant, character or string constant. Eg: # define pi=3.14;

OPERATORS Arithmetic Operators There are five arithmetic operators in C. They are OPERATOR + * / % PURPOSE Addition Subtraction Multiplication Division Modulus

RULES OF OPERATION: 1. If both the operands are floating point types whose precision differ, eg a double and float, the lower precision operand will be considered to the precision of higher one. Eg. A float and double will result in double 2. If one operand is a floating point type and the other is char or int, the char or int will get converted to floating point type. 3. If one operand is an int and another one is long int, the resultant will be long int. Type Cast: The value of an expression can be converted to a different data if desired. To do so, the expression must be preceded by the name of the desired data type, enclosed within parenthesis. ie. (datatype) expression

This type of expression is known as a cast or called type cast. i = 7; f = 5.4; ( i + f ) % 4 = 3.1; ( int ) ( i+f ) % 4 = 3; The value does not change into int but the result is converted to int. Order of Precedence a) *, /, % b) +, -

- Another important consideration in the order in which consecutive operations within the same precedence group are carried out. This is known as associativity. - Associativity is from left to right.

Unary Operators
C includes a class of operators that operate on a single operand to produce a new value. Unary minus is the most common, where a minus sign precedes a numerical constant, variable or expression. In C all numeric constants are positive only. Precedence is from left to right. Other unary operators: ++, --, sizeof

Sizeof: This returns the size of its operands in bytes. This always precedes the operand. ++i: i will be incremented first and then printed i++: i will be incremented after the office. i =2; ++ i = 3; --i= 2;

cast is also considered to be a unary operator.

Relational Operators
These operators all fall within the same precedence group, which is lower than the urinary and arithmetic operators. The associativity of these operators is left to right. The relational and equality operators are used to test or compare the value between two operands. C offers the following relational operators

Operator < <= > >= !=

Meaning less than less than or equal to greater than greater than or equal to not equal to

The relational or equality operators produce an integer result to express the condition of the comparison.
 

If the condition is false, then the integer result is zero. If the condition is true, then the integer result is non-zero.

Two Equality operators Operator == != Meaning equality not equal to

The equality operators fall into a separate precedence group, beneath the relational operators. These operators also have a left to right associativity. The resulting expressions will be of type integer, since true is represented by the integer value 1 and false is represented by the value of 0.

Logical Operators: Logical operators are used to combine two or more relations. The logical operators are called Boolean operators because the tests between values are reduced to either true or false, with zero being false and one being true. Operator ! && || NOT AND OR Meaning

In Logical operators, AND has higher precedence than the operator OR. The associativity is left to right.

Assignment Operator: The most commonly used assignment operator is =. Assignment expressions that make use of this operator is written in he form Identifier = expression where identifier usually represents a variable and expression represents a constant, a variable or a more complex expression. Eg. A = 6 Area = L* B If the two operands in an assignment expression are of different data types, then the value of the expression on the right will automatically be converted to the type of the identifier in the left. Multiple assignments are also possible in C. identifier 1 = identifier 2 = value/expression Eg: i = j = 6;

C also has additional five assignment operators i+=5 f-=g j * = ( i - 3) f/=3 i % = ( j - 2) i=i+5 f = f g; j = j * ( i 3) f=f/3 i = i % ( j 2)

Assignment operators have a lower precedence than any other operator. They right to left associativity. The assignment operator = and the equality operator == are distinctly different. The assignment operator is used to assign a value to an identifier, whereas equality operator is used to determine if two expressions have the same value. These operators cannot be used in place for one another. If the two operands in an assignment expression are of different data types, then the value of the expression on the right will automatically be converted to the type of the identifier to the left. The entire assignment expression will then be of this same data type.

Conditional Operators: This can be written in the form Expression1? Expression 2: Expression 3 When evaluating a conditional expression, expression1 is evaluated first. If expression 1 is true ( ie. If its value is non-zero), then expression 2 is evaluated and becomes the value of the conditional expression. If expression1 becomes false (ie. If its value is zero) then expression3 is evaluated and becomes the value of the conditional expression. Eg. x = (i < 10 ) ? i : 100; ORDER OF PRECEDENCE: 1. 2. 3. Unary operators Arithmetic operators Relational operators 4. Equality operators 5. Logical operators 6. Conditional operators

You might also like