Sunday, February 18, 2007

WASE BITS-WIPRO SESSION6 DT:18-02-07

VENUE : WIPRO
AUDIENCE : 2006 BATCH

Chapter 11Introduction toProgramming in C
C: A Middle-Level Language
C by Dennis ritchie at Bell in 1972
• It is a programming language closely associated with unix O.S.
Provides abstraction of underlying hardware
• operations do not depend on instruction set
• example: can write “a = b * c”, even thoughLC-3 doesn’t have a multiply instruction
Provides expressiveness
• use meaningful symbols that convey meaning
• simple expressions for common control patterns (if-then-else)
Enhances code readability
Safeguards against bugs
• can enforce rules or conditions at compile-time or run-time
C…
It is an unambiguous and machine independent definition.

It is a general purpose programming language.

C is not tied to any particular hardware or system.

BCPL and B are type less languages while C is has data types.

C is single-threaded, does not offer multiprogramming, parallel operations, syncronisations, coroutines.
C
5/9 = 0
In C integer division truncates;
Any fractional part is discarded

In C % operator can not be applied on float.

In C % operator can not be applied with real operands.

% operator takes the sign of the I operand.

Mixed mode arithmetic: result is real if one of the operand is real.
C arithmetic
6/7 = 0 -6/-7 = 0
During integer division if both the operands are of same sign the result is truncated towards zero.

If one of them is negative then direction of truncation is implementation dependant. That is

-6/7 = 0 or 1 ( machine dependant)
During modulo division the sign of the result is always the sign of the first operand.
-14%3 = -2 14%-3 = 2 -14%-3 = -2
Features of C
Fast: 32 keywords and built in functions

Robust: built in functions, operators, middle level features

Efficient: data types and operators

Extensible: libraries, functions can be added

Portable: Can be run on any machine

Structured: modules, blocks make testing and debugging easier
C
Comments are used to enhance it’s readability and understanding.

Comments do not effect the execution size and speed.

Comments aid in debugging and testing.

C is a case sensitive language

\n à new line character . It is like enter or carriage return key for typewriter
Structure of a C Program
• Functionfunction Heading(Argument list)
• Compound statementcompound statement = { …..}{ expression statements seperated by semicolon ;}
• Comments anywhere = /*……*/

Structure of a C Program
• Documentationnesting of comments not allowed
• Definition symbolic constants
• Link sectionlinks header files to source.Entire header file loaded.
• Global declaration .
• Function() { declaration part.. Exe part }



Structure…
The program will always begin by executing the main function.

The format of a C Program is

main() function starts
{……
………
………
………} function ends
Constants and Variables
Characters in C are letters, digits, special characters, white spaces

Tokens are smallest individual units of C. There are six tokens Keywords, Identifiers, strings, special, constants..

Keywords: In ANSI C there are 32 keyword

Identifiers: names of variables, functions and arrays.

Strings: sequence of characters surrounded by double quotes.
Constants and variables
Special symbols:

Constants: Fixed values that do not change during the execution of the program.
Constants are divided as
• NumericIntegerReal
• CharacterSingleString


Constants and variables
Integers: size is 2 to 4 bytes which is machine dependant.

Integers may be decimal(0..9), octal(0..7), hex(0..15)

Real: Fractional parts represented using mantissa and
exponent form

Single character constant: characters enclosed within a
single quote mark ‘5’, ‘x’

Printf(“%d”,’a’); Printf(“%c”,’a’); Printf(“%c”,97);
Constants and variables
String constants: characters enclosed in double quotes.

Backslash character constants: escape sequences like /n, /t, /f.


Variables
Variables are data names for data types.

They change during the execution of programs.

Variable names start with a letter or underscore.

variable length is 31 characters, usage is 8 characters.

variable name must not be a keyword.

White spaces are not allowed.


Data types
ANSI C supports four clesses of data types

• Derived: arrays, functions, structures, pointers.
• User defined: typedef and enum.
• Primary: int, char, float, double.
• Empty data set: void. Itr indicates type returned by functions that generate no values


Data types.. Sizes and ranges
• Charà 1 byte. -128 to 127
• Intà 2 bytes. -32768 to 32767
• Floatà 4 bytes 3.4e-38 to 3.4e+38
• Doubleà 8 bytes. 1.7e-308 to 1.7e+308


Preprocessor directives
#include

#include indicates to the compiler the nature of the library functions being used like printf().

Stdio.h is a header file consisting of library functions like printf() and scanf()

Printf() is a library function used to output information on to the screen.
Scanf() : a library function that accepts input from the k/b.
Preprocessor directives
Preprocessor directives are instructions to the compiler.
They begin with a # sign and can be placed anywhere in a program, but are most often placed at the beginning of a file.

#if #ifdef #ifndef #else #elif #include #define
#undef
#include “ “ OR #include<..>
#define identifier string
#define macroname macro substitution
#define RK “hi I am RK’
Preprocessor Directives
Printf(RK);

#define Yes 1
#define No 0
Printf(“%d %d %d”,Yes,No,Yes+No);

#ifndef HDR
#define HDR
#if
SYSTEM == MSDOS
#define HDR “msdos.h”
….#endif
Data types
Char 1 signed char 1 unsigned char 1

Int 2 signed int 2 unsigned int 2

short int 2 long int 4

Float 4

Double 8 long double 10
Data types

Sizeof() is a special operator which gives the size of the data

sizeof(char) 1

sizeof(int) 2

sizeof(float) 4

sizeof(double) 8

File.cà compileà file.objà linkà file.exe

Int data type occupies how many bytes…

.obj result in syntax errors while .exe result in linker errors.
Compilation vs. Interpretation
Different ways of translating high-level language
Interpretation
• interpreter = program that executes program statements
• generally one line/command at a time
• limited processing
• easy to debug, make changes, view intermediate results
• languages: BASIC, LISP, Perl, Java, Matlab, C-shell
Compilation
• translates statements into machine language
Ø does not execute, but creates executable program
• performs optimization over multiple statements
• change requires recompilation
Ø can be harder to debug, since executed code may be different
• languages: C, C++, Fortran, Pascal
Compilation vs. Interpretation
Consider the following algorithm:
• Get W from the keyboard.
• X = W + W
• Y = X + X
• Z = Y + Y
• Print Z to screen.

If interpreting, how many arithmetic operations occur?

If compiling, we can analyze the entire program and possibly reduce the number of operations. Can we simplify the above algorithm to use a single arithmetic operation?
Compiling a C Program
Entire mechanism is usually called the “compiler”
Preprocessor
• macro substitution
• conditional compilation
• “source-level” transformations
Ø output is still C
Compiler
• generates object file
Ø machine instructions
Linker
• combine object files(including libraries)into executable image
Compiler
Source Code Analysis
• “front end”
• parses programs to identify its pieces
Ø variables, expressions, statements, functions, etc.
• depends on language (not on target machine)
Code Generation
• “back end”
• generates machine code from analyzed source
• may optimize machine code to make it run more efficiently
• very dependent on target machine
Symbol Table
• map between symbolic names and items
• like assembler, but more kinds of information
A Simple C Program
#include
#define STOP 0

/* Function: main */
/* Description: counts down from user input to STOP */
main()
{
/* variable declarations */
int counter; /* an integer to hold count values */
int startPoint; /* starting point for countdown */
/* prompt user for input */
printf("Enter a positive number: ");
scanf("%d", &startPoint); /* read into startPoint */
/* count down and print count */
for (counter=startPoint; counter >= STOP; counter--)
printf("%d\n", counter);
}
Preprocessor Directives
#include
• Before compiling, copy contents of header file (stdio.h)into source code.
• Header files typically contain descriptions of functions andvariables needed by the program.
Ø no restrictions -- could be any C source code

#define STOP 0
• Before compiling, replace all instances of the string"STOP" with the string "0"
• Called a macro
• Used for values that won't change during execution,but might change if the program is reused. (Must recompile.)
Comments
Begins with /* and ends with */

Can span multiple lines
Cannot have a comment within a comment
Comments are not recognized within a string
• example: "my/*don't print this*/string"would be printed as: my/*don't print this*/string

As before, use comments to help reader, not to confuseor to restate the obvious

main Function
Every C program must have a function called main().

This is the code that is executedwhen the program is run.

The code for the function lives within brackets:
main()
{
/* code goes here */
}

Variable Declarations
Variables are used as names for data items.
Each variable has a type,which tells the compiler how the data is to be interpreted(and how much space it needs, etc.).

int counter;
int startPoint;

int is a predefined integer type in C.

Input and Output
Variety of I/O functions in C Standard Library.
Must include to use them.

printf("%d\n", counter);
• String contains characters to print andformatting directions for variables.
• This call says to print the variable counter as a decimal integer, followed by a linefeed (\n).

scanf("%d", &startPoint);
• String contains formatting directions for looking at input.
• This call says to read a decimal integer and assign it to thevariable startPoint. (Don't worry about the & yet.)

More About Output
Can print arbitrary expressions, not just variables
printf("%d\n", startPoint - counter);

Print multiple expressions with a single statement
printf("%d %d\n", counter, startPoint - counter);

Different formatting options:
%d decimal integer
%x hexadecimal integer
%c ASCII character
%f floating-point number
Examples
This code:
printf("%d is a prime number.\n", 43);
printf("43 plus 59 in decimal is %d.\n", 43+59);
printf("43 plus 59 in hex is %x.\n", 43+59);
printf("43 plus 59 as a character is %c.\n", 43+59);

produces this output:
43 is a prime number.
43 + 59 in decimal is 102.
43 + 59 in hex is 66.
43 + 59 as a character is f.

Examples of Input
Many of the same formatting characters areavailable for user input.

scanf("%c", &nextChar);
• reads a single character and stores it in nextChar
scanf("%f", &radius);
• reads a floating point number and stores it in radius
scanf("%d %d", &length, &width);
• reads two decimal integers (separated by whitespace), stores the first one in length and the second in width

Must use ampersand (&) for variables being modified.(Explained in Chapter 16.)
Data input and output
Library functions for input and output are getchar, putchar, scanf, printf, gets, puts
• In C there are no keyword to perform i/p and o/p. That is accomplished through library functions.
• Keyboards and printers are treated as files.
• Header file for standard input output is stdio.h

Int a;
Char b;
a = getchar(); b= getchar();putchar(a);putchar(b);
getch()à does not echo character to screen.

Formatted input and output
printf(control string,arg1,arg2…);
printf(“this is %c %s”,”a string”);
%conversion character
%format specifier(c,d,e,f,g,I,o,s,u,x)à %d %e %f %g %i %o

%u %x %D %E %G %O %I %X %U

%field width format specifier printf(“%10f”,num);

%field width.precision format code printf(“%12.5”,num);

No comments: