0 - Oop Pre-req.pdf

  • Uploaded by: FuturaCare Cuff
  • 0
  • 0
  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View 0 - Oop Pre-req.pdf as PDF for free.

More details

  • Words: 9,926
  • Pages: 136
By Muhammad Attique

 The

program that converts instructions from high level language into object code as a whole program is called compiler. It checks all violations of syntax if any and informs the programmer about their occurrence. It cannot convert source code into an object code until all the syntax errors are removed from source code.

Object oriented programming pre-requisite

2/24/2015

2

 It

is the program that executes the source program line by line rather than converting it into object code. It informs immediately about occurrence of error and errors must be removed for further execution of statements. It is time consuming task as the program has to re-interpret for execution. For example BASIC language has interpreter with it.

Object oriented programming pre-requisite

2/24/2015

3

C

is commonly known as middle level language because its syntax is like high level languages and it also provides facilities for low level programming that is why it is also called middle level language. It is a general purpose language mean all types of software can be develop using CLanguage. It was developed at AT&T Bell Laboratories in 1972. It was written by Dennis Ritchie. It was written as a part of UNIX operating system.

Object oriented programming pre-requisite

2/24/2015

4

 The

program that converts assembly language instructions into machine level instructions is called an assembler.

Object oriented programming pre-requisite

2/24/2015

5

 Keywords

are reserve words that are used by language itself. The meanings of the keywords are defined in language so we cannot use them for our own purpose. These are always in lower case alphabets. In C they are 32 in number.

auto break case

const double float continue else default enum teypedef volatile char

int for goto do

static

while

union

Object oriented programming pre-requisite

short long

struct unsigned signed switch void register sizeof extern if return

2/24/2015

6

 The

quantity that does not change itself during execution of program is called constant. It may be a numeric or non-numeric quantity.

Object oriented programming pre-requisite

2/24/2015

7

 The

quantity that changes itself during execution is called variable. The physical quantities that are numeric or non numeric and a container or place holder that holds these quantities is called variable name. A variable name remains fix at its location in memory but the quantities (values) are changed time to time. Variable names are also knows as identifiers.

Object oriented programming pre-requisite

2/24/2015

8

 A variable

name may be the combination of the alphabets (lower or upper) case, digits and a special symbol underscore (_). Examples volume1, Vol_1, vol1_ch1  First character of variable name cannot be a digit. Example volume1 allowed 1volume not allowed

Object oriented programming pre-requisite

2/24/2015

9

 No

spaces, commas, special symbols other than underscore (_) are allowed in variable name. Example Volume 1 not allowed Volume-1 not allowed Volume+1 not allowed  A variable name in upper case alphabets is different in lower case alphabets. Example A and a are two different variables  A variable must be unique in same program means a variable name defined for one data item cannot be defined for another type of data item.  Keywords are not allowed as variable name. Object oriented programming pre-requisite

2/24/2015

10

Syntax for writing a C program is called structure. It consists of three portions.  Preprocessor directives  The main () function  Body of C-Program  General Syntax of C-Program is as under #include<stdio.h> void main() { Statement1; Statement2; …………. …………. Statement; } 

Object oriented programming pre-requisite

2/24/2015

11

 Processor

Directives The instructions given to compiler before actual program are called processor directives or compiler directives. They always start with # sign. Keyword define or include is used as suffix with # sign.  Example #include<stdio.h> stdio  standard input output header file contains the functions that are related to all types of input and output. Object oriented programming pre-requisite

2/24/2015

12

The main () main function indicates the actual program to compiler. There must be main function in each program otherwise compiler generates error.  Body of C-program  All the statements of C-program are always written between curly braces { }. Starting curly brace immediately starts after main and second curly brace shows the end of C-main program. Each Cstatement ends with semicolon (;). 

Object oriented programming pre-requisite

2/24/2015

13

 Bugs

Errors of a program are called bugs. Tracking and fixing these errors is called debugging.

Object oriented programming pre-requisite

2/24/2015

14

 Syntax

Errors  Rules for writing source code are called syntax and the errors in following these rules are called syntax error. Compiler detects syntax errors first of all. If a single syntax error is present in source code compiler does not compile  That mean all syntax errors must be removed before successful compilation.  Logical Errors  The errors in the logic of a program are called logical errors Object oriented programming pre-requisite

2/24/2015

15

These errors can be categorized into two groups. 1. Link time errors 2. Run time errors o The errors that are detected by linker during linking the program with libraries are called link time errors. o On successful compilation and linking it does not mean that program is error free and it is according to the requirement of application. There may be some serious errors regarding improper/wrong output, un-expected termination of program before its end point. All of these facts show that there is certainly somewhere fault in the program 

Object oriented programming pre-requisite

2/24/2015

16

 These

faults may be due to the following  Fetal errors If program crashes un-expectedly and the sequence of execution of statements of program breaks according to the requirements of application, then this is called fetal error. For example an integer divided by zero generates undefined error; with occurrence of this type of error program’s execution is terminated. These types of errors are called fetal errors.  Non-Fetal errors If program is executing smoothly but is producing result strange this means that there is some problem in code. This is called non-fetal error. These types of errors may be occurred due to wrong input, wrong operator, wrong sequence or wrong function call etc. Object oriented programming pre-requisite

2/24/2015

17

A value used in processing is called data. It’s a plural of datum.  Types of Data 1. Alphabetic Data 2. Numeric Data 3. Alphanumeric Data  Alphabetic Data It consists of all English alphabets of both cases (lower or upper) such as “A”, “Alina”, “Baghdad ”.  Numeric Data It consists of digits from 0-9 as well as decimal point. It may be positive or negative such as 24,-78.34.  Alphanumeric Data It consists of both numeric and alphabetic data such as House No. 191. 

Object oriented programming pre-requisite

2/24/2015

18

 Data

Types The set of values and operation that can be carried on these values is called data type DATA TYPES

Primary Data Types

Secondary Data Types

int float double char

String Array union structure enum

Object oriented programming pre-requisite

2/24/2015

19

 Primary

Data Types These are the basic data types provided by language. These are also known as the primitive data types such as int, float, char etc.  Secondary Data Types The data types that are constructed using primary data types according to different needs are called secondary data types, such as array, string, structure etc. 

int The data type that consists of numeric values without decimal point is called int data type. Object oriented programming pre-requisite

2/24/2015

20

Date type

Memory Allocation (Bytes)

Value ±

Minimum

Maximum

Example

Min in integer.h

Max in integer.h

Char

1

±

-128

+127

A,-20,$,@,48

CHAR_MIN

CHAR_MAX

Char

1

+

0

255

168

Int

2

±

-32768

+32767

±48

INT_MIN

INT_MAX

short int

2

±

-32768

+32767

±49

SHRT_MIN

SHRT_MAX

unsigned int

2

+

0

65535

2128

UINT_MIN

UINT_MAX

long int

4

±

-2147483648

+2147483647

±6802128

LONG_MIN

LONG_MAX

 Float

The data type that consists of whole numbers with decimal points is called real or float data type.

Object oriented programming pre-requisite

2/24/2015

21

Float has following types with their attributes Date type

Memory Allocation (Bytes)

Value ±

Minimum

Maximum

Accuracy up to decimal points

Min in exponent

Max in exponent

Min in float.h

Max in float.h

Float

4

±

3.4*10-38

3.4*10+38

6

-38

+38

FLT_MIN

FLT_MAX

Double

8

±

1.7*10-308

1.7*10+308

12

-308

+308

DBL_MIN

DBL_MAX

long double

10

+

3.4*10-4932

3.4*10+4932

18

-4932

+4932

LDBL_MIN

LDBL_MAX

Object oriented programming pre-requisite

2/24/2015

22

•Some invalid exponential notation



Scientific /Exponential Form The real values in power notation are called scientific or exponential form, such as 1.23*1021



Its General Syntax is as:



±me±n



M: Represents Mantissa



E: Represents Exponent



N: Represents Power



±: Shows power or mantissa may be positive or negative. Real Value

Exponent Form

C-Representation of Exponent Form

100000.09990

1.0*105

1.0E5

-48.123

-4.8123*101

-4.8E1

.009212

9.212*10-3

9.212E-3

Example 4E4.8 1234 231.12e15 E10 9.0E 6.12-e5

Reason for invalidation Power Must Be Integer This is not exponent form. It is an integer value Mantissa must be from 1.0 to 10.0 Mantissa missing Exponent missing Misplace sign of exponent (power) Object oriented programming pre-requisite

2/24/2015

23

Assigning value to a variable first time at the time of declaration or after declaration is called initialization of variables. Example

int marks=75; int physics=81, math=90, comp=99; float per, sum = physics + math + comp; per=sum/3;

Object oriented programming pre-requisite

2/24/2015

24

 Comment

Statement  The statements that are ignored by compiler during compilation of program are called comment statements.  We can make a single line or paragraph as a comment.  // is used to make the single line as a comment  /* …*/ is used a paragraph comments  /* shows the beginning of the comments and */ shows the end of the comments while // comments only a single line.  Always use comments while programming it improves the readability and understandability of the logic of program. Object oriented programming pre-requisite

2/24/2015

25

 Lexemes

and Tokens  Each element of a statement is called lexeme. Example int a,b,c; float per,sum “int” “a” “b” “c” “,” “;” “float” “per”“sum” are all lexemes  While int and float are data types so one identifier is generated for them called token that is “Data Type”. Similarly token for a, b, c, per, sum is “identifier” Object oriented programming pre-requisite

2/24/2015

26

Expression  The

combination of operands and operators is called an expression. Operands may be constants or variables.  For example a*b*c is an example of an expression in which a, b and c are operands and * is operator.  Arithmetic

Operator

 The

symbol that is used to perform an arithmetic operation is called arithmetic operator.

 Types

of Operators

 Unary

Operator  Binary Operator Object oriented programming pre-requisite

2/24/2015

27

Unary

Operator

The operators that operate upon one data item are called unary operator. Example unary minus -78 it negatives the values of 78. Binary

Operators

The operator that operates upon two data items is called binary operator such as +, - etc. Types

of Expression

 Arithmetic

expression  Relational expression  Logical expression  Conditional expression  Bitwise expression Object oriented programming pre-requisite

2/24/2015

28

 Arithmetic

Expression  The combination of arithmetic operator and operands is called arithmetic expression. The operands may be constants or variables.  Example  7*d/4+g  Hierarchy of Arithmetic Operators  The order in which arithmetic operators are evaluated is called hierarchy of operator or precedence of operators.  First of all, all parenthesis are evaluated from left to right  Second /, * and are evaluated from left to right  Then + and – are evaluated from left to right. Object oriented programming pre-requisite

2/24/2015

29

 Assignment

Statement  The statement that is used to evaluate an expression and assign its value to a variable on the left side of an assignment operator (=) is called assignment statement.  Example  z=a+b;  First of all the expression a+b will be evaluated and then result will be assigned to z on left side of assignment operator (=).  Lvalue and Rvalue  The value on left hand side of assignment operator (=) is called Lvalue. Similarly the value on right hand side of assignment operator is called Rvalue. Object oriented programming pre-requisite

2/24/2015

30

 Compound Assignment

Statement If the value of an assignment statement is assigned to more than one variable on left side of assignment statement then it is called compound assignment statement.  Example a=b=c=3*d/5+56  Arithmetic Assignment Operator The operator that performs the arithmetic operation on variable and assigns the values to same variable is called arithmetic assignment operator.  Examples  + = -= /= *= %= Object oriented programming pre-requisite

2/24/2015

31

 Compound Assignment

Expression If arithmetic operation is performed on variable without writing it on either side and also assign it a value after arithmetic operation then it is called arithmetic assignment statement. a=a+b;  a+ =b; c=c/7; c/=7;  Increment Decrement Operators The operator that increases the value of one in the variable is called increment operator. It is a unary operator. It is represented by (++). Similarly the operator that decreases the value of one from a variable is called decrement operator. It is also a unary operator. It is represented by (--). Object oriented programming pre-requisite

2/24/2015

32

 Prefix  Postfix  Prefix

Increment Operator  The increment operator that is used to increment the values of a variable before it has been used in expression is called prefix increment operator. G. Syntax a=10; b=++a;

++X Equals

Object oriented programming pre-requisite

a=10; a=a+1; b=a;

2/24/2015

Result b=11 a=11

33

 Postfix

Increment Operator  The increment operator that increases the value of one after the variable has been used in expression is called postfix increment operator.  G. Syntax X++

a=10; b=a++;

Equals

a=10; b=a; a=a+1;

Object oriented programming pre-requisite

2/24/2015

Result b=10 a=11

34

The conversion of one data type into another during execution of program is called casting or type casting Implicit

Casting

Arithmetic operation can only be performed when both of the operands of arithmetic operator have the same data type. If both of the operands have different data type then lower order data type with respect to bytes in memory is converted into higher order data type and on becoming same data types arithmetic operation is performed. This type of casting is called implicit casting. Object oriented programming pre-requisite

2/24/2015

35

 Explicit

Casting The casting with the help of cast operator is called explicit casting. This type of casting is performed on programmer’s willing rather than compiler’s. float b,a; a=3.141593; b=(int) a;  Overflow and Underflow Each variable is allocated fixed number of bytes in memory. Each byte has limited capacity to hold constants/literal. So each variable has minimum and maximum range to hold data. If we assign the value beyond the minimum range an error is generated is called underflow similarly if we assign the value that is beyond the maximum range an error is generated called 36 overflow. Object oriented programming pre-requisite

2/24/2015

 Examples

char a, b; a=128; //over flow greater than its maximum range (DOS mode) b=-129; //under flow less than its minimum range (DOS mode)  Output

Anything received from computer is called output.  Output Function The function that is used to output some data from program is called output function.

Object oriented programming pre-requisite

2/24/2015

37

printf() function is used to output all types of data such as int, float, char etc on console. The symbol “()” must be read as function.  G. Syntax of printf() printf(“Control String”, (list of arguments from which values are to be output)/constants);  Control String It may consist any or all of following things. 1 Message String 2 Format Specifiers 3 Escape Sequence

Object oriented programming pre-requisite

2/24/2015

38

 Message

String The actual message that is as it is output on console without alteration is called message string.  Format Specifiers The special characters that specify the data type being input (in case of using input function) or output. The first character of format specifiers is always % second character specify the data type. Following is the complete list of format specifiers with their data type they specify.

Object oriented programming pre-requisite

2/24/2015

39

Format Specifier %d %i %u %o %x %X %c %s %f %e %E

%g %G

Data Type Used For Decimal (the number system having base 1o ) Integer Unsigned integers (non-negative numbers including memory addresses) Octal (the number system having base 8) Hexadecimal (the number system having base 16)* Hexadecimal (the number system having base 16)* Character String Float Float having exponent (small e will be print if used in output function) Float having exponent (capital E will be print if used in output function) Float –large values (small e will be print if used in output function) Float-large values (capital E will be print if used in output function)

Object oriented programming pre-requisite

2/24/2015

40

*

In hexadecimal 0-9 are same but 10-11 are represented by English alphabets like a,b,c,d,e,f. if small x is used it will print small a-f alphabets and if capital X is used it will print capital alphabets from A-F.  Escape Sequence  The special characters that are not printed themselves but are used to control output on console are called escape sequence. They are prefixed with control character “\”. Complete list of escape sequence is as under with their description.

Object oriented programming pre-requisite

2/24/2015

41

Escape Description Sequenc e \n Next line

Example

printf(“Ayesha\nAslam”);

Output

Ayesha Aslam

\t

Spaces equals of tab printf(“\tHafeez Janjua”);

Hafeez Janjua

\a

Alert (a light beep printf(“\aAAMIR ATTARI”); sound)

\b

One curser back

A beep sound then prints AAMIR ATTARI 48

\r

Carriage return printf(“Naila48\rKhurshi (moves cursor start d”); of current line)

\\

Prints \

printf(“\\Raja\\”);

\Raja\

\”

Prints “

printf(“\”Mithhu\””);

“Mithhu”

%%

Prints %

float per=82.00; printf(“My %% =%f”,Per);

My %=82.00

printf(“1\b48”);

Object oriented programming pre-requisite

2/24/2015

Khurshid

42

List

of Argument

 It

consists of the list of variables or constants that are to be print on console. My First Program write a program to output “I am Pakistani” on console. void main() { printf("I am Pakistani"); } It’s a complete program but on compiling (Press ALT+F9)* it generates an error printf() should have a prototype. So we must include its header file before main (). Object oriented programming pre-requisite

2/24/2015

43

We can use any statement that waits for something to occur for example use getch () function that waits for the input of character until we enter any character from keyboard. Now the program will look like this #include<stdio.h> void main() { printf("I am Pakistani"); getch(); }  On compiling again it prompts for prototype of getch() use its appropriate header file just right click on getch() it will show you it’s appropriate header file i.e so include now conio.h then program will look like this. 44 

Object oriented programming pre-requisite

2/24/2015

#include #include<stdio.h> void main() { printf("I am Pakistani"); getch(); } Why? It should show current output not previous so you can use another helping function that will erase previous output from console that function is clrscr().

Object oriented programming pre-requisite

2/24/2015

45

*2 write a program to output “I am Pakistani” on console. #include<stdio.h> #include void main() { clrscr(); printf("I am Pakistani"); getch(); }

Object oriented programming pre-requisite

2/24/2015

46

 Steps

1.

for C-program

Editing

Coding a program is called editing. Save the program with extension .c, .cpp (Plus Plus), .x etc.

2.

Compiling

Checking syntax errors and converting the program into object code is called compiling. Goto compile menu and select menu item compile or press (Alt+F9). Compiler generates another file with extension .obj in which all calls to functions are leaved as unresolved symbols.

3.

Linking

As compiler leaves the function calls as unresolved symbols. Linker links these functions with their libraries to place the coding of their function into object file. On successful linking the file with libraries, a file is generated that is ready to execute, which is called an .exe (executable). Object oriented programming pre-requisite

2/24/2015

47

4.

Running

Executing the program is called running the application (Program). In Borland Turbo editor press Ctrl+F9 to run the application. By default when we run the application it first compiles then links it with libraries then executes it. So only pressing Ctrl+F9 or selecting menu run will compile, link and execute the program on single event. Program #3 write a program to initialize marks in three subjects print their sum and average? Program #4 write a program to initialize two variables print them before and after exchange their contents. Program#5 write a program to input radius of a circle print out its area and circumference. Use formula area= πR2 Circumference= 2 πR

(use π=3.14)

Object oriented programming pre-requisite

2/24/2015

48

 Initialize

mean assigning a value to a variable at your own but this is not actual practice in real programming environment. Values are input at the run time (at the time of execution of program). So we must have to use input function to input values.  Input Anything given to computer is called an input.  Input function  The function that is used to input data into computer program is called input function. There are several input functions that are used to input specific data types. For example getch() we have discussed above is used to input a character. scanf() is also used to input all types of data. Object oriented programming pre-requisite

2/24/2015

49

G. Syntax scanf(“format specifiers”, list of argument to which values are to be input each prefixed with &);  Example int a,b,c; scanf(“%d”,&a); scanf(“%d”,&b); scanf(“%d”,&c); OR scanf(“%d%d%d”,&a,&b,&c); // Don’t use ”,” between format specifiers. 

Object oriented programming pre-requisite

2/24/2015

50



Since the value of π is 3.14 we have to use it in the statement why not we declare it inside of the program as constant. There are two ways to define such types of constants. #define directive const qualifier #define directive It is used to define a variable as constant. The variable will be replaced with its constant inside whole program where it has been used except in comment statements and in control statements used in output function G. Syntax #define PI 3.14 It is not necessary to use capital word but is convention to differentiate for other variables. There is no assignment operator used to assign value nor semicolon is used to terminate the statement. It is not statement it is #define directive.Object oriented programming pre-requisite 2/24/2015 51

 const

qualifier It is also used to define a variable as constant. This is just like declaration of variable as constant since the variable declared with const keyword is constant so we cannot change its contents in program.  G. Syntax const float PI=3.14; Since it is declaration statement so always use assignment operator (=) and statement terminator (;) Program #6 write a program to input three side of a triangle print out its area and circumference. Use formula

Object oriented programming pre-requisite

2/24/2015

52

 Program

#7 write a program to input temperature in Fahrenheit convert and print it into centigrade  Program#8 write a program to input radius of a sphere print out its volume and surface area using formula  Program#9 write a program to input initial velocity, time and acceleration of a car find and print distance covered by car using formula (S=Vit+ at2)  Program#10 write a program to input length and width of rectangle find and print its area and perimeter.  Program#11 write a program to input distance in Kilometers convert and print it into Meters, Centimeters, Feet, and Inches.

Object oriented programming pre-requisite

2/24/2015

53

 12

write a program to input distance of object from lens (p) and distance of image from lens (q) find and print the focal length of lens using formula  13 write a program to input amount in rupees find and print it how many 100, 50, 20, 10, 5, 2, and 1 rupee notes are required. Give priority to big notes first.  14 write a program to input a number having five digits print out the sum of its individual digits and reverse of the number.  15 write a program to input two numbers print out their contents before and after exchange without using third variable.

Object oriented programming pre-requisite

2/24/2015

54

Points

to be Noted

Always use appropriate data types for variable declaration it may loss the data or memory.  Always use appropriate format specifiers in printf () and scanf () although it is not syntax error but it leads to serious logical error.  Don’t use extra format specifiers in printf () and scanf () it does not generate syntax error but you may confuse while input or output from strange results.  Don’t use commas (,) in scanf () although it is not syntax error but the process of input is halted and remaining variables are left garbaged.  Always initialize the variables with appropriate values otherwise garbage values are assigned to them. 

Object oriented programming pre-requisite

2/24/2015

55

Object oriented programming pre-requisite

2/24/2015

56

 The

languages in which programs are written according to predefined ways and there is one staring point and one end point for execution are called structured programming languages. So C is a structured programming language. In any structured programming or in other era of programming languages, there are three types of programming structures.  Sequential Structure  Conditional Structure  Iterative/Looping/Repititional Structure

Object oriented programming pre-requisite

2/24/2015

57

 Sequential

Execution Structure The statements of a program are executed in order in which they are written, is called sequential execution structure. Program starts its execution from main () and completes the execution of all statements in order from first statement to last statement and after executing last statement, the execution of program is terminated.  Control Statements As by default all the statements of a program are executed in order in which they are written but we can change the order of execution with the help of control statements. The statements that are used to shift control of execution from one statement to other in the same program are called control statements. Object oriented programming pre-requisite

2/24/2015

58

 Examples

goto statement  if statement  if –else statement  nested if – else statement  switch statement  while statement  for statement  do – while statement 

Some of the control statements are unconditional control statements while others are conditional control statements. Object oriented programming pre-requisite

2/24/2015

59

 Un-Conditional

Control Statements The control statements that shift the control from one statement to other in the same program without checking the condition are called un-conditional control statements.  Example goto label  goto Statement It is un-conditional control statement used to transfer control from one statement to other without evaluating the condition. The use of goto statement is not appreciated by programmers. Because it is just burden for compiler not the necessity of transferring control

Object oriented programming pre-requisite

2/24/2015

60



G. Syntax

goto

label;

The label is an identifier placed anywhere in the program post fixed with colon (:) and the control is immediately transferred to that label from goto without executing remaining statements. #include

#include<stdio.h> void main() { clrscr(); int Num1,Num2,Sum; goto l1;

l2:

scanf("%d",&Num1); goto l3;

l5:

Sum=Num1+Num2; goto l6;

l3:

printf("\n Enter Number2="); goto l4;

l1:

printf("\n Enter Number1="); goto l2;

l4:

scanf("%d",&Num2); goto l5;

l6:

printf("\n The Sum of %d and %d = %d", Num1,Num2,Sum); getch();

}

Object oriented programming pre-requisite

2/24/2015

61

 Conditional

Control Statements The statements that are used to shift control of execution from one statement to other statement in the same program after checking the condition are called conditional control statements.  Example       

if statement if –else statement nested if – else statement switch statement while statement for statement do – while statement

Object oriented programming pre-requisite

2/24/2015

62

Conditional Execution Structure The execution of statements of program on the behalf of conditional control statements is called conditional execution structure.  Iterative/Looping/Repeatitional L Structure The statements of a program can also be executed repeatedly for fixed number of iterations is called iterative execution structure.  Relational Operator The operator that is used to compare two data items and it always produces result true or false is called relational operator.  Relational Expression The expression in which relational operators are used is called relational expression. It always produces result true or false. The relational expression can also be called as test, condition or conditional expression. 63 2/24/2015 Object oriented programming pre-requisite 

Examples of operators with their description are as under

Relational operator

Used for

Relational Expression A=10,B=20,C=30 A>B

Result of Relational Expression

>

Greater than

>=

Greater or Equal C >=B

True

<

Less than

C
False

<=

Less or Equal

A<=C

True

!=

Not Equal

B!=C

True

==

Equal

A==C

False

Object oriented programming pre-requisite

2/24/2015

False

64

 Difference

Between (=) & (==) The assignment operator (=) is used in assignment. It assigns the Rvalue to Lvalue. While the relational comparison operator (= =) checks whether both side of the relational comparison operator are equal or not. If both sides are equal, generates result true otherwise false. In C zero means always false and non-zero means always true.

Object oriented programming pre-requisite

2/24/2015

65

 It

is conditional control statement that is used to execute or ignore statement or set of statements after checking the condition. If the condition in if statement is true the statement or set of statements that comes immediately after if statement are executed otherwise ignored and control is shifted to next statement(s) without executing immediately coming statement(s) after if statement. G. Syntax if (condition) Statement -1; Statement-2; Object oriented programming pre-requisite

2/24/2015

66

Object oriented programming pre-requisite

2/24/2015

67



Execution of Syntax If the condition in if statement is true then the statement-1 is executed and the control is shifted to statement-2. If the condition in if statement is not true the statement-1 is ignored and control is shifted to directly statement-2. Whether the condition in if statement is true or false statement-2 will execute at all. If statement is affected (will execute or ignore) only on statement-1 in this case but if we want to execute more than one statements in case of true of condition, we have to follow this style. if (condition) { Statement -1;

Statement-2; ... Statement-N; } Object oriented programming Statement-M;

pre-requisite

2/24/2015

68

2 write a program to input any positive number print out whether it is odd or even. #include #include<stdio.h> void main() { clrscr(); int Num; printf("\nEnter Any Positive Number="); scanf("%d",&Num); if (Num%2==0) printf("\nThe Number is Even"); if (Num%2!=0) printf("\nThe Number is Odd"); getch(); } Object oriented programming pre-requisite

2/24/2015

69

 Some 



Precautions while using if statement

if statement by default has control on one statement (each control statement shows this behavior by default). If more statements are to be executed/ignored on the behalf of if statement, use block (place statements in pair of curly braces { }). Any non-zero number as condition will propagate result true and zero will generate result false.



if (0)

//Always False



if(-1)

//Always True



if(1)

//Always True



if(-0)

//Always False



if(0.00)

//Always False



if(-56.67)

//Always True



if(48)

//Always True

Object oriented programming pre-requisite

2/24/2015

70





   





Use of assignment (=) rather than relational comparison operator (= =) will generate always true result except assignment of zero (0). if(0=0) //Syntax error Lvalue cannot be constant (Lvalue required) if(Num=0) //Always False if(Num=1) //Always True if(Num=26) //Always True if(Num=-2.5) //Always True Condition can also be made on simple arithmetic operation then the result will depend on the result of an operation. If the result is zero (0) test will be consider as false otherwise true. int Num=10; if(Num%2) false



//False; since the remainder is 0 so 0 yields

int Num=5; if(Num%2)

//True; since the remainder is 1 so 1 yields true

Object oriented programming pre-requisite

2/24/2015

71

 Normally

semicolon is not used after if statement but if somewhere it is used it is not syntax error. A null statement is the statement that performs nothing. int Num=3; if(Num%2); /*Well! It executes well but the output is nothing */

Object oriented programming pre-requisite

2/24/2015

72

 write

a program to input any year print out whether it is leap year or not.

#include #include<stdio.h> void main() { clrscr(); int Year; printf("\nEnter Any Year="); scanf("%d",&Year); if (Year%4==0) printf("\nThe Year is Leap"); if (Year%4!=0) printf("\nThe Year is not Leap"); getch(); } Object oriented programming pre-requisite

2/24/2015

73



Write a program to input co-efficient of quadratic equation find and print out its roots using formula . The quadratic equation is ax2+bx+c. Program should be so efficient to output real and imaginary roots. #include #include<stdio.h> #include void main() { clrscr(); float a,b,c,X1,X2,Xreal,Ximag,Disc; printf("\nEnter Co-efficients of Quardatic Equation="); scanf("%f%f%f",&a,&b,&c); Disc=b*b-4*a*c; if (Disc>=0) { printf("\nThe Roots are Real"); X1=(-b+(sqrt(Disc)/(2*a))); X2=(-b-(sqrt(Disc)/(2*a))); printf("\nX1=%f\nX2=%f",X1,X2); } if (Disc<=0) { printf("\nThe Roots are Imaginary"); Xreal=-b/(2*a); Ximag=sqrt(-Disc)/(2*a); printf("\nX1=%f+i%f",Xreal,Ximag); printf("\nX2=%f-i%f",Xreal,Ximag); } getch(); } 2/24/2015 Object oriented programming pre-requisite

74

5.write a program to input any English alphabet print out whether it is vowel or consonant.  For input of character we can use scanf () function. There are also other so many functions you can get advantage of getch () function. You can use following functions for input of character also.  getche()  getchar() 

getch(), getche() and getchar() all of the functions are used to input single character from console and assign the inputted values into character variable. The difference is that getch () and getche () belong to conio.h header file while getchar () belongs to stdio.h header file and also the inputted character from getch is not displayed on console while other two functions echo (display) the inputted character on console. Object oriented programming pre-requisite

2/24/2015

75

#include #include<stdio.h> void main() { clrscr(); char ch; int isVowel=0;

printf("\nEnter Any Alphabet"); ch=getchar(); if(ch=='a')

isVowel=1;

if(ch=='A')

isVowel=1;

if(ch=='e')

isVowel=1;

if(ch=='E')

isVowel=1;

if(ch=='i')

isVowel=1;

if(ch=='I')

isVowel=1;

if(ch=='o')

isVowel=1;

if(ch=='O')

isVowel=1;

if(ch=='u')

isVowel=1;

if(ch=='U')

isVowel=1;

if (isVowel==1) printf("\nEntered Alphabet is Vowel"); if (isVowel==0) printf("\nEntered Alphabet is Consonant"); getch();

}

Object oriented programming pre-requisite

2/24/2015

76

6.

7.

8.

9.

write a program to input any positive number having five digits print out whether it is palindrome (a number whose reverse is equal to it) or not. write a program to input any number from 100 to 999. Print out whether it is Armstrong number or not. Armstrong number is the number whose sum of its all digits after cube is equal to it. For example consider 153. write a program to input cost price, sale price of a shop keeper, print our whether he earned profit, loss or not profit no loss and how much? write a program to input two numbers and an arithmetic operator perform operation on the numbers according to arithmetic operator. (Make a simple calculator) Object oriented programming pre-requisite

2/24/2015

77

10



write a program to input any year after 1900. Program should print what will be the day on its first January. According to Georgian calendar it was Monday on first January of 1900. What happens if we have one condition and two choices and we have to select one of them? The simple if statement does not provide this style of structure the best choice for this type solution is if-else statement.

Object oriented programming pre-requisite

2/24/2015

78



if–else Statement This is another form of if statement it has one condition and two blocks (choices). First block comes immediately after if statement and second block comes after keyword else.

G. Syntax if (condition) Statement -1; else Statement-2; Multi-Statements can be places in any of the block such as if (condition) { Statement -1; Statement-2; ... Statement-N; } else { Statement -1; Statement-2; ... Statement-N;

}

Object oriented programming pre-requisite

2/24/2015

79

Object oriented programming pre-requisite

2/24/2015

80

 11

write a program to input any positive integer print out whether it is odd or even. Use if–else statement.

#include #include<stdio.h> void main() { clrscr(); int Num; printf("\nEnter Any Positive Number="); scanf("%d",&Num); if (Num%2) printf("\nThe Number is Odd"); else printf("\nThe Number is Even"); getch(); } Object oriented programming pre-requisite

2/24/2015

81



12

write a program to solve quadratic equation using if-else statement.

#include #include<stdio.h> #include<math.h> void main() { clrscr(); float a,b,c,X1,X2,Xreal,Ximag,Disc; printf("\nEnter Co-efficients of Quardatic Equation="); scanf("%f%f%f",&a,&b,&c); Disc=b*b-4*a*c; if (Disc>=0) { printf("\nThe Roots are Real");

X1=(-b+(sqrt(Disc)/(2*a))); X2=(-b-(sqrt(Disc)/(2*a))); printf("\nX1=%f\nX2=%f",X1,X2); } else { printf("\nThe Roots are Imaginary"); Xreal=-b/(2*a); Ximag=sqrt(-Disc)/(2*a); printf("\nX1=%f+i%f",Xreal,Ximag); printf("\nX2=%f-i%f",Xreal,Ximag); } getch();

Object oriented programming pre-requisite

2/24/2015

82

 Nested

if Statement

Another if statement in if statement’s true or false block is called nested if statement. The structure of nesting of if statement may be nesting of if statements only or nesting of else if. Whatever the way we are nesting is called nested if statements.

Object oriented programming pre-requisite

2/24/2015

83

Object oriented programming pre-requisite

2/24/2015

84

13

14

15

16

write a program to input percentage marks of the student in all subjects of B.Sc. suppose the subjects have following chart of marks. English 100, Pak. Study + Islamic Study 100, Any Optional Subject1 200, and Other Optional2 subject 400. (The other Optional2 subject can be divided into two optional having 200 each). Mean to say that total marks for B.Sc. should be 800. Find out percentage and print its grade according to university laws. Develop a simple arithmetic calculator using nested if-else statement. 15 write a program to input three numbers print out greater among them use nested if statement structure. 16 write a program to input any English alphabet print out whether it is vowel or not (using nested if-else statement).

Object oriented programming pre-requisite

2/24/2015

85



switch Statement It is also conditional control statement that can be used as an alternative to nested if structure as nested if structure becomes complex where several conditions are to be checked. It has one condition and several choices upon which one has to be select. A value (expression) of switch statement is matched to each choice (case) upon successful matching the set of statements for that case is executed. Only integral values can be checked in switch stamen for example 1, 4, ’C’, ‘&’ can be checked in cases, while 5.6, “AAMIR” are invalid case literals.



G. Syntax

switch(Expression) { case 1: statement(s); break; case 2:

statement(s); break; …….. default: statement; } Object oriented programming pre-requisite

2/24/2015

86

 Execution

of G. Syntax

On evaluating the expression from switch statement its values is matched with each case one by one. If it is matched with some case, the statements of that case are executed and break statement shifts the control outside of switch statement. If the break statement is missing in any case, upon successful matching of that case it will execute the block of that particular case and next blocks of other cases will also be executed until next break comes.

Object oriented programming pre-requisite

2/24/2015

87

Consider the following program; #include #include<stdio.h> void main() { clrscr(); int a=3; switch(a) { case 1:

printf("\nOne"); case 2: printf("\nTwo"); break; case 3: printf("\nThree"); default: printf("\nGreater than Three"); } getch(); }

Object oriented programming pre-requisite

2/24/2015

88

As the value of the expression is 3; case 1 is false, case 2 is false and the case 3 is true, its block will be executed. But case 3 is missing break at its end it will continue to execute the statements of next block. The output will be. Three Greater than Three  default statement is executed when no case is matched. It is optional statement and may be placed anywhere in the body of switch statement. Consider the following program; 

Object oriented programming pre-requisite

2/24/2015

89

#include #include<stdio.h> void main() { clrscr(); int a=2; switch(a) { case 1: printf("\nOne"); break; default: printf("\nValue is other than three"); break; case 3: printf("\nThree"); break; case 2: printf("\nTwo"); } getch(); }

Object oriented programming pre-requisite

2/24/2015

90

write a program to make simple calculator by using switch statement. 18 write a program to input any alphabet print out whether it is vowel or not. (Use switch statement) 19 write a program to ask choice from user Enter 1 for Conversion Fahrenheit temperature into centigrade Enter 2 for conversion of centigrade into Fahrenheit. And precede the choice entered by user at run time. 17

Object oriented programming pre-requisite

2/24/2015

91

 Conditional

Operators

These operators are the alternate to simple if–else statement. They are “?” and “:”, “?” is used in the meaning of then and “:” is used as an else.  Conditional

Expression

The expression in which conditional operators are used is called conditional expression.  G.

Syntax

(condition)? True block statement(s) : false block statement(s) ;

Object oriented programming pre-requisite

2/24/2015

92

For example consider the program in if–else structure. int a=10,b; if (a>20) b=50; else b=100; Above code can be coded using conditional operators. int a=20,b; (a>=20)?b=50:b=100; 20 write a program to input any character print out whether it is odd or even using conditional operators. Object oriented programming pre-requisite

2/24/2015

93



1 2

3



Logical Operators The operators that are used to check more than one relational expression as a combined condition are called logical operators. They always produce result true or false. There are three logical operators used in C-language. And Operator (&&) Or Operator (||) Not Operator (!) Logical Expression The expression in which logical operators are used is called logical expression. It always produces result true of false. Object oriented programming pre-requisite

2/24/2015

94

 Logical

AND Operator (&&) The operator that produces result true if both of the operands of the logical && operators are true otherwise false, is called logical AND (&&) operator.

T

F

T F

F F

Exp2

Exp1

T F

21 write a program to input three numbers print out greater among them use logical operators. Object oriented programming pre-requisite

2/24/2015

95

22

23

write a program to input percentage of the student print out its grade according to percentage criteria. write a program to input any character print out whether it is digit or not. Use conditional and logical operators.

Object oriented programming pre-requisite

2/24/2015

96

 Logical

OR Operator (||) The operator that produces the result false if both of the operands are false otherwise true is called logical (||) operator. T

F

T T

T F

Exp2

Exp1

T F

Object oriented programming pre-requisite

2/24/2015

97

24

25

26

write a program to input any English alphabet print out whether vowel or not. Using logical operator the solution is easier than switch statement. write a program to input any character print out whether it is lower case alphabet, upper case alphabet, digit or special symbol. 26 write a program to input any alphabet if it is in lower case converts it into upper case and if it is in upper case convert it into lower case.

Object oriented programming pre-requisite

2/24/2015

98

 Logical

NOT Operator (!) The operator that inverses the result is called logical (!) operator. It is unary operator. It inverts the true result into false and false into true. 27 write a program to input any year print out whether it is vowel or not. Program should be so generic.

End of Chapter#2 Object oriented programming pre-requisite

2/24/2015

99

CHAPTER # 03 Object oriented programming pre-requisite

2/24/2015

100

Some times we need to execute statement(s) repeatedly until some given condition is true. How can we accomplish this? One option was, that we have used in previous chapter goto+if statement. But that was not the exact solution we need another option that must be so generic. Fortunately C provides statements for this type of executional structure, called loops.

Object oriented programming pre-requisite

2/24/2015

101

 Loop

The statement that executes statement or set of statements until specific amount of time is reached, is called loop. The statements may be executed until fixed or unfixed amount of time. Means to say that we may know in advance the number of iterations of loop or we may not know in advance the number of iterations of loop. The loops that have fixed number of iterations are called fixed or counter controlled loops and the loops that have no fixed number of iterations are called sentinel (someone to keep watch for some anticipated event) control loops.

Object oriented programming pre-requisite

2/24/2015

102

 Parts

of loop  Initialization  Finalization/Condition/Test  Statement(s)  Increment/decrement /step Size/Jump Size  Initialization means the start point of loop; from where loop has to start execution.  Finalization means the end point of loop; condition or test until it is true.  Statement(s) means the actions that are performed during execution of loop  Increment/decrement means that step size or jump to reach up to finalization. Object oriented programming pre-requisite

2/24/2015

103

Types

of loops in C

while loop  do while loop  for loop 

 while

loop The loop that executes the statement(s) until given condition remains true is called while loop. It checks the condition first then executes the statement(s), that’s why it is called pre-test loop.

Object oriented programming pre-requisite

2/24/2015

104

 G.

Syntax initialization; while(condition) { statement(s); increment/decrement; }

Object oriented programming pre-requisite

2/24/2015

105



1

write a program to print out counting from 1 to 10

#include #include<stdio.h> void main() { clrscr(); int i=1;

while(i<=10) { printf("%d\n",i); i++; } getch();

}

Execution 1 2 3 4

5 6 7 8 9 10

Object oriented programming pre-requisite

2/24/2015

106

2 write a program to print out all even numbers up to 100. #include #include<stdio.h> void main() { clrscr(); int i=0; while(i<=100) { printf("%d\n",i); i+=2; } getch(); } Object oriented programming pre-requisite

2/24/2015

107

3 write a program to print out all odd numbers between two numbers entered by user. #include #include<stdio.h> void main() { clrscr(); long int Counter,Start,End; printf("\nEnter Staring Point="); scanf("%ld",&Start);

printf("\nEnter Ending Point ="); scanf("%ld",&End); Counter=(Start%2)?Start:Start+1; while(Counter<=End) {

printf("%ld\n",Counter); Counter+=2; } getch(); }

Object oriented programming pre-requisite

2/24/2015

108

4

write a program to print out following series.

2048 1024

512

256

128

64

32

16

8

4

2

1

#include #include<stdio.h> void main() { clrscr(); int Counter=2048; while(Counter>0) { printf("%d\t",Counter); Counter/=2; //Counter=Counter/2; } getch(); } Object oriented programming pre-requisite

2/24/2015

109

5

write a program to sum up following series. 1+2+3+4+5+ - - -+N = , Also print the series.

#include #include<stdio.h> void main()

{ clrscr(); long int Counter=1,N,Sum=0; printf("\nEnter The Maximum Limit = "); scanf("%ld",&N); while(Counter<=N) { printf("%ld+",Counter); Sum+=Counter; Counter++;

//Sum=Sum+Counter;

//Counter=Counter+1;

} printf("\b=%ld",Sum); getch(); } Object oriented programming pre-requisite

2/24/2015

110

6 write a program to product the following series. 1*4*7* - - -*N= #include #include<stdio.h> void main()

{ clrscr(); long int Counter=1,N,Product=1; printf("\nEnter The Maximum Limit = "); scanf("%ld",&N); while(Counter<=N) { printf("%ld*",Counter); Product*=Counter;

//Product=Product*Counter;

Counter+=3; //Counter=Counter+3; } printf("\b=%ld",Product); getch(); } Object oriented programming pre-requisite

2/24/2015

111

write a program to input any positive integer print out its table up to 10.

7

#include #include<stdio.h> void main() { clrscr(); int N,Prod,Counter=1; printf("\nEnter the Number = ");

scanf("%d",&N); while(Counter<=10) { Prod=N*Counter;

printf("\n%d * %d\t=\t%d",N,Counter,Prod); Counter++; } getch();

}

Object oriented programming pre-requisite

2/24/2015

112

8

write a program to input any positive integer print out its factorial. Factorial is the product of sub-sequent integers up to 1. Factorial can be calculated by making loop from 1 to N or from N to 1. Following solution is from 1 to N.

#include #include<stdio.h> void main() { clrscr(); int N,Counter=1; long int Fact=1; printf("\nEnter Any +ve Integer = "); scanf("%d",&N); while(Counter<=N) { Fact=Fact*Counter;

Counter++; } printf("\nThe Factorial of %d = %ld",N,Fact); getch(); }

Object oriented programming pre-requisite

2/24/2015

113

write a program to sum up to following series. ½+2/3+3/4+ - - -+n/(n+1)=

9

#include #include<stdio.h> void main() { clrscr(); int N; float Sum=0.0; int Counter=1; printf("\nEnter Limit = ");

scanf("\n%d",&N); while(Counter<=N) { Sum=Sum+Counter/(Counter+1.0); printf("%d/%d+",Counter,Counter+1);

Counter++; } printf("\b=%f",Sum); getch(); } Object oriented programming pre-requisite

2/24/2015

114

10

write a program to sum up following series.

1/3-3/5+5/7-7/9+ - - - ±n/(n+2)= 

11

Where n is the limit entered run time

write a program to input any positive number print out its reverse using while loop

Object oriented programming pre-requisite

2/24/2015

115



break statement The break statement is used to terminate the execution of switch statement or loop. It is usually used with if statement in the body of loop. Whenever control is shifted to break statement it simply shifts control outside of loop or switch statement without executing further statements.



continue statement The continue statement is used to shift the control back to loop without executing remaining statements for that particular iteration. #include #include<stdio.h> void main() { clrscr(); int i=-1; while(i<100) { i++; if(i%2==0) continue; printf("%d\t",i); } getch(); }

Object oriented programming pre-requisite

2/24/2015

116



Sentinel control loop The loops that have no fixed number of iterations are called sentinel control loops. All previous loops in programs were having fixed number of iterations. Consider a following program.



do while loop The loop that executes statements first then checks the condition is called dowhile loop. It executes at least once whether the given condition is true or false. It executes statements until given condition remains true. Since it checks the condition in last after executing the block it is also known as post test loop. #include #include<stdio.h> void main() { clrscr(); int i=1;

do { printf("%d\n",i); i++; } while(i<=10); getch();

Object oriented programming pre-requisite

2/24/2015

117



for loop This is another form of while loop, that executes the statement(s) until given condition remains true. It is commonly known as counter loop. Like while loop it checks the condition first then executes the statement(s), it is also pre-test loop. The execution of for loop is same as while loops only syntax is different. It has several syntaxes. Most general syntax is as under.



G. Syntax

for(initialization;test;increment/decrement) { Statement(s); }

Object oriented programming pre-requisite

2/24/2015

118

 Infinite

loops

When the condition of the loop never false and it continue to execute, this is called infinite loop.  Nested

loops

The loops inside loops are called nested loops. Loops are placed in the body of loops. First loop that has another loop in its body is called outer loop while the second loop that is inside body of outer loop is called inner loop. Any loop from three loops (while, do while, for) can be used a outer loop as well as inner loop. For the simplicity of implementation normally for loops are used as nested loops but this is not always practice.

For example consider the following program. int i,j;

for(i=1;i<=3;i++)

//Outer Loop

for(j=1;j<=3;j++)

//Inner Loop

printf(“\n%d\t%d”,i,j);

Object oriented programming pre-requisite

2/24/2015

119

End of Chapter #3

Object oriented programming pre-requisite

2/24/2015

120

 Some

times length of a program reaches up to hundreds even thousands of lines. These types of programs are difficult to manage in debugging and testing point of view. we can divide the code into small units so that they can be written, tested, and managed by all ways independent of each others. C provides this type of structure, called function/macro/recursion.  Function Function is an independent program that is written to perform a specific task and is executed by main() or any other function. Each C program is basically a function, so main() is also a function from which scheduler (the task of operating system) starts the execution of program. Object oriented programming pre-requisite

2/24/2015

121

 Types

of Function 1. Built in functions 2. User defined functions The functions that are available within the language library are called built in functions. For example pow(), abs(), getch()are examples of built in functions. The functions that are written by programmer/developer (or impropriate term user) are called user defined functions. We can write our own function that performs the functionality same as pow() function. This self written function will be called user defined function. Object oriented programming pre-requisite

2/24/2015

122

 Ingredients 1. 2. 3.

of Function

Arguments Parameters Return value

 Arguments

The values that are passed to function on which function may perform calculations are called arguments of function. A function can receive none, one or more than one values of any data type.  Parameters

The values that are received by function are called parameters. The parameters are always received in order with respect to data type, in which they are passed. Incoming data type may or may not received by higher or lower data type but if received it may lead to loss of data. Object oriented programming pre-requisite

2/24/2015

123



Return Value The result that a function returns to its caller is called return value. For example in previous chapter program we have used function pow(). It receives two arguments first one is the number, second one is the power of that number. Res=pow(x,y); If we pass 3, 4 as arguments. It will return result 81 i.e. 34. Res=pow (3, 4); Res=81 If we call the pow() function in main(), then the main function will be called “caller function” and the value retuned by pow() will be received by main() function (being caller) and is assigned to variable Res in this case (if assigned) to left side of assignment operator. Object oriented programming pre-requisite

2/24/2015

124

 Signatures

of a Function Function Name Number of Parameters Order of Parameters with Respect to their Data Types  Function Name The name of function is unique identifier for function. All the rules of a variable are equally applied on function name.  Number of Parameters It means how many parameters are received by function.  Order of Parameters with Respect to their Data Types Object oriented programming pre-requisite

2/24/2015

125

 The

parameters are also uniquely identified by order of data type. For example a function with name SUM receives two arguments i.e. first arguments of type int and second of type float similarly another function with same name SUM receives two arguments i.e. first arguments of type float and second of type int. These two definitions of function with same name are unique due to the order of the arguments. This is also called function overloading.

Object oriented programming pre-requisite

2/24/2015

126



Consider the following example that is used to input two numbers and pass these numbers to function. Function will return their sum to main() and final sum will be printed in main() function.

#include #include<stdio.h>

int Sum(int Num1,int Num2) { int Result; Result=Num1+Num2; return Result;

} void main() { clrscr(); int N1,N2,Res; printf("\nEnter Two Numbers\n"); scanf("%d%d",&N1,&N2); Res=Sum(N1,N2); printf("\nSum=%d",Res); getch(); } Object oriented programming pre-requisite

2/24/2015

127



If the function is defined in another file simply include the file with #include directive same as header files.

write a program to input marks in five subjects pass them to function. Function should return the percentage to caller function. Caller function will print the percentage #include #include<stdio.h> float Function(int,int,int,int,int); void main() { clrscr(); int M1,M2,M3,M4,M5;

float per; printf("\nEnter Marks in Five Subjects\n"); scanf("%i%i%i%i%i",&M1,&M2,&M3,&M4,&M5); per=Function(M1,M2,M3,M4,M5); printf("\nPercentage=%f",per);

getch(); } float Function(int S1,int S2,int S3,int S4,int S5) { return (S1+S2+S3+S4+S5)/5.0; }

Object oriented programming pre-requisite

2/24/2015

128

 Returning

More Values from Function

Function can return only one value explicitly, but we can return more than one values from function. There are two mechanisms to pass values to function.  Pass

by value  Pass by reference 

Pass by reference can be of two types 



Pass by reference of an argument Pass by address of an argument

Object oriented programming pre-requisite

2/24/2015

129



Pass by Value

In the above all programs, all the arguments passed to function are passed by value. This means that only values of arguments are passed to function and any change with that value in the function definition will not affect the original contents of arguments in caller function. Consider the following example. #include #include<stdio.h> void Fun(int); void main() { clrscr();

int X=10; printf("\n X before call to function = %d ",X); Fun(X); printf("\n X After

call to function = %d",X);

getch();

} void Fun(int X) { X=X+10; } Object oriented programming pre-requisite

2/24/2015

130

Output will be X before call to function = 10 X After call to function = 10 The value of X before and after call to function is same because the value (10) of X was send to function Fun () and 10 was received in the parameter X in functional declarator. The parameter X is local variable to function Fun() any change in the local variable will not affect the X in main().

Object oriented programming pre-requisite

2/24/2015

131



Pass by Reference

When we declare variable it is allocated fixed number of bytes depending upon the data type of variable. Since each byte of memory has unique address so each variable has an address. That is the first byte address of allocated bytes (both in Little Endean Order and Big Endian Order). We can check the address of variables by using the address operator (&) with unsigned integer (because addresses are always positive). ). Consider following example. #include #include<stdio.h>

void main() { clrscr(); int X=10,Y=20; printf("\n value of X = %d ",X); printf("\n address of X=%u",&X); printf("\n value of Y = %d ",Y); printf("\n address of Y=%u",&Y); getch(); Object oriented programming pre-requisite

2/24/2015

132

 Reference

Another name of same memory address is called references. Since it is another name of same memory address any change with reference or original variable will affect the contents of same memory address.  Pointers

Pointer is an object that holds the address of another object. There is some difference in reference and pointer. Reference refers to same location but don’t have its own memory address while pointer has its own address. Pointer is an object that points to data type. Object oriented programming pre-requisite

2/24/2015

133

 sizeof

Operator The operator that returns the number of bytes occupied by data item is called sizeof operator.

G. Syntax sizeof(dataitem); 

Pass by address When arguments are passed by addresses and received by pointers any change in the pointer can modify the original contents of arguments in caller function.

Object oriented programming pre-requisite

2/24/2015

134

 Default/Optional

Arguments

The arguments that are not necessary to pass in functional call are default or optional arguments. These arguments have default values actually when we omit to pass their values they use their default values. Their default values are set in function declarator or function prototype.  Function

Overloading If there are several functions of same name but their signatures are different, is called function overloading or the several definitions of same function are called function overloading. Signature includes number of parameters, order of parameters with respect to their data types return type does not matter in function overloading. Object oriented programming pre-requisite

2/24/2015

135

All codes written in chpater#4 will be included in syllabus till above mentioned article End of mid term syllabus

Object oriented programming pre-requisite

2/24/2015

136

Related Documents

0 - Oop Pre-req.pdf
November 2019 14
Oop
November 2019 35
Oop Exercise
June 2020 16
Introduction Oop
November 2019 33
Oop Programs
June 2020 5
Upgrading Oop
June 2020 8

More Documents from ""

0 - Oop Pre-req.pdf
November 2019 14