1 programming in c– an overview. 2 c-programming general purpose language developed by dennis...

54
1 Programming in C– An Overview

Post on 19-Dec-2015

219 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

1

Programming in C– An Overview

Page 2: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

2

C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs

(1972). First used as The Systems Language for The UNIX operating system.

Why ‘C’1. C is a SMALL Language

Small is beautiful in programming Fewer key words but powerful

2. C is the Standard Developmental Language for personal computers.Much of : MS-DOS & OS/2

Many windowing packages, Data Base PGMS, Graphic

Libraries & other Large Application Packages are written in ‘C’

Page 3: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

3

3. ‘C’ is Portable - easily moved from machine to machine.

Provides a standard library of functions that work the same on all machines.

Built in Preprocessor - helps isolate any system dependent code.

4. ‘C’ is Terse - very powerful set of operators.

Can accomplish in 1 statement what might require many statements in another language.

A Terse language explicitly magnifies the underlying productivity of the programmers.

5. ‘C’ is Modular - Supports Structured Programming.

Functions - Internal - External

Supports user - Defined Libraries of Functions

Supports Privacy by using “Static” storage Class within files.

Page 4: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

4

Lexical Elements

• C is a language.– Characters + Punctuators + Rules.

• C Program is viewed as a sequence of Tokens separated by White Space (i.e., spaces, tabs, new lines).

– Keywords.

– Identifiers.

– Constants.

– String constants.

– Operators.

– Punctuators.

Page 5: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

5

Keywords

• Reserved words.

• Cannot be redefined or used in other contexts.

• Case sensitive.

• See pg. 46 in your text.

Page 6: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

6

Identifiers

• The names of variables, functions, labels and other user-defined items are called identifiers.

• May be any length.– ANSI C – First 31 characters are recognized.

• Cannot be the same as a keyword or library function.

• Case sensitive.– E.g., count, Count and COUNT are three separate

identifiers.

Page 7: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

7

• The first character must be a letter or an underscore, and subsequent characters must be either letters, digits or underscores.

Correct Incorrect

Count1 1count

test23 hi!there

high_balance high . . . Balance

• Identifiers should be chosen to reflect their use in the program.

Page 8: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

8

Constants

• Integer A) Decimal 0-9

• B) Octal 0-7

• C) Hexidecimal 0-F

Page 9: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

9

Floating Point: Need . Or E format

23.65 .897 2e+03 2.34e-05

Character: Any single printable character in single

Page 10: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

10

String Constants

• Character(s) enclosed in Double Quotes

• “A” and ‘A’ or not the same.

• “A” is actually followed by the Null character.

“Hello” is really “Hello\0”

Page 11: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

11

“a string of text”

“” // the null string

“ ” // a string of a blank character

“ a = b + c; ” // nothing is executed

Page 12: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

12

Operators

• Arithmetic Addition +• Subtraction -• Multiplication *• Division / • { int/int – int}

• Modulus %

• 5%3 = 2 Integer Remainder• 3%9 = 3

Page 13: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

13

• Relational Operators:

< <= > >= != ==

Allow us to create Boolean expressions

which can control program execution.

Logical Operators: Not !

And &&

Or ||

Page 14: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

14

Sometimes the meaning of the operator must be its determined by context.

a) scanf (“% d”, variable);

b) x = y % z;

a) % a conversion character

b) % a modulus operator

Page 15: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

15

Punctuators

• They are located by the compiler as tokens and are used to separate language elements.

Parentheses ( ) Braces { }

Commas , Semicolons ;

int main(void){

int a, b=3, c=6;a = 17 * (b + c);…

}

Page 16: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

16

Terms

• Source code– Text of a program.– The input to the C compiler.

• Object code– Translation of the source code of a program into

machine code. Output from the Compiler.– The input to the linker.

• Linker– A program that links separately compiled modules

into one program.– The output is an executable program.

Page 17: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

17

• Library– The file containing the standard functions that

a program can use.

• Compile time– The time during which a program is being

compiled.

• Run time– The time during which a program is executing.

Page 18: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

18

Compilation

• A compiler translates source code into machine code.

• One high-level instruction can correspond to several machine instructions.

Ex: x = (y + 3) / z;

• Control structureswhile, repeat, if-then-else, case, …

Page 19: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

19

• Procedures/subroutines/functions.

Must create machine language code to:– Copy input parameter values .– Save return address.– Start executing at beginning of invoked

routine.– Copy output parameter values at end of

procedure.– Set PC to return address.

Page 20: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

20

• Lexical Analysis: Break up command syntax into logical components, called tokens, and discard comments, spaces, etc. Ex: total=sum + 55.32 contains five tokens,

total, =, sum, +, and 55.32

• Parsing: Decide how tokens are related.

Ex: sum + 55.32 is an arithmetic expression, total = sum + 55.32 is an assignment

statement.

Page 21: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

21

• Code generation:

Generating machine instructions to

implement each high-level command.

It is important to optimize the code.

Page 22: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

22

1. X = Y+Z;

2. W =X+Z;

After line 1, X and Z are already in registers, so no need to re- load the registers for line 2, therefore execution is faster. Less retrieval time.

The resulting machine language program,called object code, is written to disk.

Page 23: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

23

Library and Linking

• Most programs include calls to various functions contained in C's standard library. The object code(from C compiler) contains “holes” due to these missing parts.

• A Linker links the object code with the code for the missing functions to produce an executable image(load module).

Page 24: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

24

Library and Linking

Linker: combines the result of compiling different pieces of the program separately. If pieces refer to each other, these references cannot be resolved during independent compilation.

procedure p main

Refers to x

Declares x

Invokes p

Page 25: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

25

Two separate files

int count;                       #include <stdio.h>

void display(void);        extern int count; int main(void)    void display(void){ { count = 10; printf(“%d”, count); display(); } return 0;}

Page 26: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

26

C’s Memory Map

• Separate compilation.

• Conceptualized memory map of a C program. Memory for the program, memory for the data.

StackHeap-DynamicGlobal variablesProgram code

Page 27: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

27

A Hello World Program

/*The traditional first program in honor of Dennis Ritchie who invented C at Bell Labs in 1972.*/

#include <stdio.h>

int main(void) //main function{ printf(“Hello, world!\n”); return 0;}

Hello, world!

Page 28: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

28

Format of the Function:

Preprocessor Directives //Here we include any libraries required by the program.

:

int main ()

{

Declarations ; //Here we list any data variable declarations.

Body of Function //Here is the source program version of the algorithm.

}

Main Function: Program will have 1 main function where Execution Begins & Ends.

Pre-Defined Functions: Already Exist - Part of the Language. Programmer uses them to do predefined

Activities - Input/Output.

User-Defined Functions: Functions written by the programmer. Created to do specific task(s).

e.g. - Given Hours worked & payrate;

Calculate Employee salary.

Page 29: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

29

Preprocessing directives

• Before compilation takes place the preprocessor modifies the source code that is input to the compiler.

includes files - #include define constants - #define

• All preprocessor directives begin with a # sign.• Each preprocessing directive must be on its own

line. #include <stdio.h> #include <stdlib.h> //wrong

Page 30: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

30

#include

• General Syntax:

– #include <filename> e.g. #include <stdio.h>The preprocessor looks for the file only in standard places.

– #include “filename” e.g. #include “utility.h”The preprocessor first search the file in the current directory and then in other system-dependent places.

Page 31: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

31

• General Syntax: Symbolic Constant

#define macro-name char-sequence

e.g. #define PI 3.14

• The preprocessor changes all occurrence of the identifier PI to 3.14.

e.g. printf(“PI = %f\n”, PI) printf(“PI = %f\n”, 3.14)

• A symbolic constant is easily changed later.• By convention, a symbolic constant is written in

capital letters.

#define

Page 32: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

32

#define ONE    1#define TWO    ONE+ONE

#define E_MS "standard error on input\n"printf(E_MS);

#define XYZ this is a testprintf("XYZ"); xyz

standard error on input

#define LONG_STRING "this is a very long \string that is used as an example"

Page 33: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

33

# define: can be placed anywhere in your source code.

usually place at the beginning of your source code before main( ) function.

Where you place them determines their SCOPE.

SCOPE: The segment of code that “knows about” the existence of the symbolic constants and/or

macros you have created.

e.g., If place at the beginning of your source file, then the SCOPE is the entire

file.

Page 34: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

34

Header Files: Are joined with your source code by the Preprocessing Directive #.

Why - often reason is that they contain the FUNCTIONAL PROTOTYPES (FP’s) of functions that the program wishes to call. - If the FP’s are not available then the program can’t call (use) those functions.

Functional Prototype: The “Heading” of the function.

Contains the Name and return type of the function. The number & type of values that may be passed to the function (Formal parameters).

The Compiler needs the FP’s of invoked functions to perform its job.

Page 35: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

35

Comments• Multi-Line comments

– May be placed anywhere in a program.

– May not be nested.

/* this is a multilinecomment */

x = 10+ /* add the numbers */5; //correct

/* this is an outer comment   x = y/a;  /* this is an inner comment - and causes an error */*/ //wrong

Page 36: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

36

• Single-Line Comments

– A single-line comment can be nested within a multi-line comment.

– All but the most obvious functions should have a comment at the top that states what the function does, how it is called, and what it returns.

// this is a single-line comment

/* this is a // test of nested comments. */

Page 37: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

37

A Depth Program#include <stdio.h>

int main(void)

{

int inches, feet, fathoms; //declarations

fathoms = 7;

feet = 6 * fathoms;

inches = 12 * feet;

printf(“Wreck of the Hesperus:\n”);

printf(“Its depth at sea in different units:\n”);

printf(“ %d fathoms\n”, fathoms);

printf(“ %d feet\n”, feet);

printf(“ %d inches\n”, inches);

}

Wreck of the Hesperus:Its depth at sea in different units: 7 fathoms

42 feet 504 inches

Page 38: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

38

Declaration

• A variable is declared to be of a type. This enables the compiler to:

– Set aside the appropriate amount of memory to hold the variable.

– Defines what operations are permissible with that variable.

• All variables must be declared before they are assigned values and used in statements.

• Declaration end with a semicolon.

Page 39: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

39

Assignment• Allows the work and processing of data to achieved.

variable; Variable = constant;

function call;expression; [contains any/all of above

joined by operators]

• Multiple assignments. Right to Left Association:1. C = 0

A = B = C = 0; 2. B = (C = 0)3. A = (B = (C = 0))

Page 40: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

40

Compound Assignments

+=, -=, *=, /=, %=

General Form:Variable += Exp; Variable = Variable + Exp;Variable -= Exp Variable = Variable - ExpVariable *= Exp Variable = Variable * ExpVariable /= Exp Variable = Variable * ExpVariable %= Exp Variable = Variable % Exp

x += 10; x = x +10;x -= 100; x = x - 100;

Page 41: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

41

Data Types: See more in Chap. 6

Variables - Locations in memory we create which can hold data.

Variables have a specific type. Type defines what sort of data is allowed

to be stored in the variable.

Integer Types: int, short int, long int

Real Types: float, double, long double

Text Types: Char 1 keystoke (1 symbol) Stringmultiple characters

Page 42: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

42

Initialization• When variables are declared, they may also be

initialized. Typically, constants or constant expressions are used to initialize a variable. General Syntax

type variableName = constant;

A) Integer Constant:e.g. x = 100; correct 100 = x; wrong

B) Real: 1.63 double1.63F float1.63L long double

e.g. float x, y;

x = 1.0; y = 2.0; x/y = 0.5;

Page 43: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

43

C) Char Single symbol in single quotes.

e.g. Char Letter;

Letter = ‘A’.

Letter = ‘9’;

D) String Multiple symbols in double quotes.

e.g. “This is a string constant”

Page 44: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

44

• General Syntax:

– scanf (“format string”, Arguments)• Interactive Input: get data from user entering via keyboard.

– fscanf (f, “format string”, Arguments)• File Input: get data that is stored in file F.

– sscanf (s, “format string”, Arguments)• String Input: get data from string S.

• Return value: If error occurs, return value is EOF (usually -1), Otherwise returns the number of successful assignments of data to the arguments.

Input Predefined Functions

Page 45: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

45

• Unsuccessful Input:

– EOF (End of File) is reached before ALL arguments have been assigned data, if so the value EOF (-1) is returned.

– Data Mismatch: The input data does not match the control string specifications. (e.g., indicated data would be integer and the data actually entered was REAL).

Page 46: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

46

• SCANf - Interactive Input

– User enters data with keyboard when program interrupt occurs.

– Input data treated as an input stream of characters.

– Arguments of the scanf are addresses.

scanf(“%d”, &x);

Page 47: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

47

String Input#include <stdio.h>

int main(void){  char str[80];   printf("Enter a string: ");  scanf(''%s", str);

  printf("Here's your string: %s", str);  

return 0;}

Page 48: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

48

Output Predefined Functions• General Syntax:

– printf (“control string”, Arguments)• Writes to terminal.

– fprintf (f, “control string”, Arguments)• Writes to another file.

– sprintf (s, “control string”, Arguments)• Writes to string s.

• Return Value: If EOF occurs, return value is -1, Otherwise returns the number of successful assignments of data to the arguments.

Page 49: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

49

Format Specifiers

Contain Conversion Specification Characters:e.g., d - decimal data c - character

f - floating point s - string

printf("I like %c %s", 'C', "very much!");

Contain Text:

int Sum = 500;

printf (“The Sum is %d”, Sum);

New Line - printf (“hello, \n world”);

Tab - printf (“hello, \t world \n”)

The Sum is 500

Page 50: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

50

ASIDE: scanf float use %fdouble use %lf

printf float or use %fdouble

Format Specifiers (cont.)

Page 51: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

51

Field Width Specification

printf (“more numbers: %7.1f %7.2f %7.3f”, 4.0, 5.0, 6.0);

Field width. Precision

# of columns output # of decimal digits to right

including dec. pt. of decimal pt.

more numbers:_ _ _ _ 4.0 _ _ _ 5.00 _ _ 6.000

Page 52: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

52

Character Data:

printf (“%c%5c/n%4c”, ‘x’, ‘y’, ‘z’);

x_ _ _ _ y

_ _ _z

Page 53: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

53

Looping - Iteration

• Categories: Conditional Loops: while do-while

Counting Loop : for

• While Statement:

while (Expression) {

Body of Loop

}

while (scanf(“%d”, &d)==1){

printf(“%d”, d);}

Page 54: 1 Programming in C– An Overview. 2 C-Programming General Purpose Language Developed by Dennis Ritchie of Bell Labs (1972). First used as The Systems Language

54

How Terminate Loop?• Dummy Data Logic:

– User enter a value that can’t be successfully converted.

• End-of-file Logic:– Indicate all data has been entered by typing

EOF signal.UNIX ctrl + d

MS DOS ctrl + z

• break - Exit from Loop immediately.

• continue - Jump to Bottom of Loop.