Oop lec 1

44
Lecture No 1 COMSATS Institute of Information Technology Review of Basic Programming Concepts 1 Object Oriented Programming

description

 

Transcript of Oop lec 1

Page 1: Oop lec 1

Lecture No 1COMSATS Institute of Information

Technology

Review of Basic Programming Concepts

1 Object Oriented Programming

Page 2: Oop lec 1

Basics of Typical C Program Development Environment

Object Oriented Programming2

A program development environmentThe languageC Standard Library

Page 3: Oop lec 1

Six phases to be executed

Object Oriented Programming3

EditPreprocessorCompileLinkLoadExecute

Page 4: Oop lec 1

Stages of compilation

Object Oriented Programming4

Preprocessing

Performed by a program called the preprocessor

Modifies the source code (in RAM) according to preprocessor directives (preprocessor commands) embedded in the source code

Strips comments and white space from the code

Page 5: Oop lec 1

Object Oriented Programming5

Compilation

Performed by a program called the compilerTranslates the preprocessor-modified source

code into object code (machine code)Checks for syntax errors and warnings

o If any compiler errors are received, no object code file will be generated.

o An object code file will be generated if only warnings, not errors, are received.

Page 6: Oop lec 1

Object Oriented Programming6

Linking

Combines the program object code with other object code to produce the executable file.

The other object code can come from the Run-Time Library, other libraries, or object files that you have created.

Saves the executable code to a disk fileo If any linker errors are received, no executable file

will be generated.

Page 7: Oop lec 1

Simple c program

Object Oriented Programming7

/* Filename: product.c Description: This program prompts the user for two integer values then displays

their product. */

#include <stdio.h>

int main( void )

{

int value1, value2, product ;

printf(“Enter two integer values: “) ;

scanf(“%d%d”, &value1, &value2) ;

product = value1 * value2 ;

printf(“Product = %d\n”, product) ;

return 0 ;

}

Page 8: Oop lec 1

Anatomy of c program

Object Oriented Programming8

program header comment

preprocessor directives (if any)

int main ( void ) { statement(s) return 0 ; }

Page 9: Oop lec 1

Object Oriented Programming9

A comment is descriptive text used to help a reader of the program understand its content.

Lines that begin with a # are called preprocessor directives (commands).

Every program must have a function called main. This is where program execution begins.

A left brace (curly bracket) -- { -- begins the body of every function. A corresponding right brace -- } -- ends the function body.

Page 10: Oop lec 1

Object Oriented Programming10

int value1, value2, product;Declaration of variables

Variables: locations in memory where a value can be stored

int means the variables can hold integers (-1, 3, 0, 47)

Variable names (identifiers)value1, value2, productIdentifiers: consist of letters, digits (cannot begin with a

digit) and underscores( _ )Case sensitive

Declarations appear before executable statementsIf an executable statement references and undeclared

variable it will produce a syntax (compiler) error

Page 11: Oop lec 1

Object Oriented Programming11

scanf("%d%d", &value1,&value2);Obtains values from the user

scanf uses standard input (usually keyboard)This scanf statement has two arguments

%d - indicates data should be a decimal integer&value1 - location in memory to store variable

When executing the program the user responds to the scanf statement by typing in a number, then pressing the enter (return) key

Page 12: Oop lec 1

Object Oriented Programming12

= (assignment operator)Assigns a value to a variableIs a binary operator (has two operands)product = value1 * value2;

Variable receiving value on leftprintf( “Product is %d\n", product);

Similar to scanf%d means decimal integer will be printedproduct specifies what integer will be printed

Page 13: Oop lec 1

Arithmetic

Object Oriented Programming13

Arithmetic operators:

Rules of operator precedence:

C operation

Arithmetic operator

Algebraic expression

C expression

Addition + f + 7 f + 7

Subtraction - p – c p - c

Multiplication * bm b * m

Division / x / y x / y

Modulus % r mod s r % s

Operator(s) Operation(s) Order of evaluation (precedence)

() Parentheses Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses “on the same level” (i.e., not nested), they are evaluated left to right.

*, /, or % Multiplication,Division, Modulus

Evaluated second. If there are several, they are evaluated left to right.

+ or - Addition Subtraction

Evaluated last. If there are several, they are evaluated left to right.

Page 14: Oop lec 1

Decision Making: Equality and Relational Operators

Object Oriented Programming14

Executable statementsPerform actions (calculations, input/output of data)Perform decisions

May want to print "pass" or "fail" given the value of a test grade

if control structureSimple version in this section, more detail laterIf a condition is true, then the body of the if

statement executed 0 is false, non-zero is true

Control always resumes after the if structureKeywords

Special words reserved for CCannot be used as identifiers or variable names

Page 15: Oop lec 1

Decision Making: Equality and Relational Operators

Object Oriented Programming15

Standard algebraic equality operator or relational operator

C equality or relational operator

Example of C condition

Meaning of C condition

Equality Operators = == x == y x is equal to y

not = != x != y x is not equal to y Relational Operators > > x > y x is greater than y

< < x < y x is less than y

>= >= x >= y x is greater than or equal to y

<= <= x <= y x is less than or equal to y

Page 16: Oop lec 1

Control Structures

Object Oriented Programming16

Control Flow In C, three ways to specify sequence of statement executionSequential ExecutionConditional ExecutionIterative Execution

Page 17: Oop lec 1

Conditional Execution

Object Oriented Programming17

One-way selection or ifTwo-way selection or if-elseMultiple Selection or nested if

Page 18: Oop lec 1

One-way selection or if

Object Oriented Programming18

If(expression) statement1;If(x>10) y=z/x; y=z*x;If(x>y) printf(“the largest is %d”,x);

Page 19: Oop lec 1

Two-way selection or if-else

Object Oriented Programming19

If(expression) statement1; else statement2;If(x>y) printf(“the largest is %d”,x); else printf(“the largest is %d”,y);

Page 20: Oop lec 1

Multiple Selection or nested if

Object Oriented Programming20

If(condition1) { if(condition2) statement1; } else statement2;

Page 21: Oop lec 1

Iterative Execution

Object Oriented Programming21

The while statementThe for statementThe do-while statement

Page 22: Oop lec 1

The while statement

Object Oriented Programming22

While(expression) statement1;

#include<stdio.h>int main(){ Int k, num, maximum=10; k=1; while(k<=maximum) { scanf(“%d”, &num); printf(“%4d”, num); k++; }return 0;}

Page 23: Oop lec 1

The for statement

Object Oriented Programming23

for(expression1;expression2;expression3) statement1;expression1: initial valueexpression2: boolean expressionexpression3: update of expression

Page 24: Oop lec 1

Example

Object Oriented Programming24

#include<stdio.h>int main(){ int sum, n, i; sum = 0; scanf(“%d”, &n); for(i=1; i<=n; i++) sum = sum + i; printf(“Sum=%d\n”,sum); return 0;}

Page 25: Oop lec 1

The do-while statement

Object Oriented Programming25

do statement1 while(expression);

Page 26: Oop lec 1

Example

Object Oriented Programming26

#include<stdio.h>int main(){ int sum, num; sum = 0; num=1; do { sum = sum + num; num++; } while(num <= 10); printf(“Sum=%d\n”,sum); return 0;}

Page 27: Oop lec 1

Other Control Structures

Object Oriented Programming27

switchbreakcontinue

Page 28: Oop lec 1

Example

Object Oriented Programming28

#include<stdio.h>int main(){ int n; printf(“Enter an integer value\n” ); scanf(“%d”, &n); switch(n) { case 1: printf(“The value is 1\n”); break; case 2: printf(“The value is 2\n”); break; default: printf(“The value is neither 1 nor 2\n”); } return 0;}

Page 29: Oop lec 1

Functions

Object Oriented Programming29

An independent set of statements for performing some special tasks

AttributesName of function (user-defined)ParametersVariable declaration (if any)The body of function

Page 30: Oop lec 1

Divisions of Function

Object Oriented Programming30

Prototype int largest(int x, int y);

Definition Head function itself

Invocation large = largest (x, y);

Page 31: Oop lec 1

Types of Function

Object Oriented Programming31

System-supplied functionsTo instruct system to accomplish specific

operationsSaves programmers time to writing own functionsCompletely debugged, efficient and always

produce precise outputReduce source codeprintf(“%d”, x);

User-defined functionsDefined by programmer as part of source codeResult-type user-defined-name(parameters)

Page 32: Oop lec 1

User-defined function

Object Oriented Programming32

#include<stdio.h>int retlarge(int num1, int num2);int main(){ int num1, num2, large; scanf(“%d%d”, &num1, &num2) ; printf(“%d %d\n”, num1, num2) ; large = retlarge(num1, num2); printf(“large = %d\n”, large); return 0;}int retlarge(int x, int y){ if (x>y) return(x); else return(y);}

Page 33: Oop lec 1

Methods for transmitting parameters

Object Oriented Programming33

Passing by valuetreated as local variablesthe initial value is obtained by copying the

values of associated actual parametersPassing by location

passing by address or referencelinking actual parameters to formal

parameters by passing address of actual parameters from the calling program to called program

Page 34: Oop lec 1

Arrays

Object Oriented Programming34

Group of elements of same type. Collection of similar data type stored in contiguous memory location. To refer to an element, specify

Array namePosition number

Format:arrayname[ position number ]

First element at position 0n element array named c:

c[ 0 ], c[ 1 ]...c[ n – 1 ]

Name of array (Note that all elements of this array have the same name, c)

Position number of the element within array c

c[6]

-45

6

0

72

1543

-89

0

62

-3

1

6453

78

c[0]

c[1]

c[2]

c[3]

c[11]

c[10]

c[9]

c[8]

c[7]

c[5]

c[4]

Page 35: Oop lec 1

Declaring Arrays

Object Oriented Programming35

When declaring arrays, specifyNameType of arrayNumber of elementsarrayType arrayName[ numberOfElements ];

Examples:int c[ 10 ]; float myArray[ 3284 ];

Declaring multiple arrays of same typeExample:int b[ 100 ], x[ 27 ];

Page 36: Oop lec 1

Object Oriented Programming36

Initializersint n[ 5 ] = { 1, 2, 3, 4, 5 };

If not enough initializers, rightmost elements become 0

int n[ 5 ] = { 0 } All elements 0

If too many a syntax error is produced syntax error

C arrays have no bounds checkingIf size omitted, initializers determine it

int n[ ] = { 1, 2, 3, 4, 5 }; 5 initializers, therefore 5 element array

Page 37: Oop lec 1

Object Oriented Programming37

Character arraysString “first” is really a static array of charactersCharacter arrays can be initialized using string literals

char string1[] = "first"; Null character '\0' terminates strings string1 actually has 6 elements

It is equivalent tochar string1[] = { 'f', 'i', 'r', 's', 't', '\0' };Can access individual characters

string1[ 3 ] is character ‘s’Array name is address of array, so & not needed for

scanf scanf( "%s", string2 );

Reads characters until whitespace encountered Can write beyond end of array, be careful

Page 38: Oop lec 1

Array Subscripting Formula

Object Oriented Programming38

Address of i-th element = address of 0-th element + i * (size of type)

Assuming declaration int intarr[10];Assuming address of array intarr is located

at address 10 in memoryAccessing element intarr[5] can be

calculated by formula:Address of i-th element = 10 + 5 * 2 = 20

Page 39: Oop lec 1

Pointers

Object Oriented Programming39

Pointers are variables that contain memory addresses as their values.

A variable name directly references a value.

A pointer indirectly references a value. Referencing a value through a pointer is called indirection.

A pointer variable must be declared before it can be used.

Page 40: Oop lec 1

Object Oriented Programming40

Memory can be conceptualized as a linear set of data locations.

Variables reference the contents of a locationsPointers have a value of the address of a given

locationA declaration int intval=10;

Then int ptr can be set as int *ptr;Pointing to intval by ptr = &intval;Address of intval assigned to ptr, not contents!

Page 41: Oop lec 1

& and *

Object Oriented Programming41

When is & used?

When is * used?

& -- "address operator" which gives or produces the memory address of a data variable

* -- "dereferencing operator" which provides the contents in the memory location specified by a pointer

Page 42: Oop lec 1

Pointers and Function

Object Oriented Programming42

Pointers can be used to pass addresses of variables to called functions, thus allowing the called function to alter the values stored there.

If instead of passing the values of the variables to the called function, we pass their addresses, so that the called function can change the values stored in the calling routine. This is known as "call by reference" since we are referencing the variables.

Page 43: Oop lec 1

Passing pointers to function

Object Oriented Programming43

#include <stdio.h>

void exchange ( int *a, int *b ) ;

int main ( )

{

int a = 5, b = 6;

printf("a=%d b=%d\n",a,b) ;

exchange (&a, &b) ;

printf("a=%d b=%d\n",a,b) ;

return 0 ;

}

Page 44: Oop lec 1

Object Oriented Programming44

void exchange( int *a, int *b )

{

int temp;

temp= *a; *a= *b; *b = temp ;

printf ("a=%d b=%d\n", *a, *b);

}

Results:

a=5 b=6

a=6 b=5

a=6 b=5