Top Banner
ES202 Computer Fundamentals and Programming 2 Prepared by: Roel Lauron Text Book: Forouzan, Behrouz A. and Gilberg, Richard F. Computer Science, A Structured Programming Approach Using C Thomson Course Technology, USA. Latest Edition References: Any books in C/C++ or websites. See the syllabus for more details Revised October 2012
235
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Es202 Lecture Notes

ES202Computer Fundamentals and Programming 2

Prepared by:Roel Lauron

Text Book: Forouzan, Behrouz A. and Gilberg, Richard F. Computer Science, A Structured Programming Approach Using C Thomson Course Technology, USA. Latest Edition

References: Any books in C/C++ or websites. See the syllabus for more details

Revised October 2012

Page 2: Es202 Lecture Notes

C Language Elements

Function MainEvery C program has a main function. This

is where program execution begins. Body- the remaining line of the program in

the body.Braces {} – enclose the body of the

function.- indicates the beginning and end of the function main.

Page 3: Es202 Lecture Notes

C Language Elements

Two parts of the function body:1. Declarations – the part of the program

that tells the compiler the names of memory cells in a program needed in the function, commonly data requirements identified during problem analysis.

2. Executable statements – derived statements from the algorithm into machine language and later executed.

Page 4: Es202 Lecture Notes

FIGURE 2-2 Structure of a C Program

Page 5: Es202 Lecture Notes

C Language ElementsYour First Program

#include <stdio.h>#include <conio.h>

main() { printf("Hello World!\n");getch();}

Page 6: Es202 Lecture Notes

C Language Elements

Reserved WordsIn C, a reserved word is defined as the word that has special meaning in C and cannot be used for other purposes.

Examples: int, void, double, return

Page 7: Es202 Lecture Notes

C Language ElementsPunctuation Marks/* */ -(slash asterisk) used to enclose a single line

remarks.“ -(double quotation) used to display series of

characters, and initializing string constant.; -(semicolon) statement separator, -(comma) used to separate one variable to

another= -(equal sign) used as assignment operator‘ -(single quotation) used for initializing character

expression& -(ampersand) used as address operator{} -(open/close braces) denotes the beginning and

end of the program.

Page 8: Es202 Lecture Notes

2-3 IdentifiersOne feature present in all computer One feature present in all computer languages is the identifier. Identifiers languages is the identifier. Identifiers allow us to name data and other allow us to name data and other objects in the program. Each identified objects in the program. Each identified object in the computer is stored at a object in the computer is stored at a unique address. If we didn’t have unique address. If we didn’t have identifiers that we could use to identifiers that we could use to symbolically represent data locations, symbolically represent data locations, we would have to know and use we would have to know and use object’s addresses. Instead, we simply object’s addresses. Instead, we simply give data identifiers and let the give data identifiers and let the compiler keep track of where they are compiler keep track of where they are physically located.physically located.

Page 9: Es202 Lecture Notes

C Language Elements

Reserved WordsIn C, a reserved word is defined as the word that has special meaning in C and cannot be used for other purposes.

Examples: int, void, double, return

Page 10: Es202 Lecture Notes

Variables, Data Types and Constants

Naming Conventions (Identifiers)

1. Names are made up of letters and digits.2. The first character must be a letter.3. C is case-sensitive, example ‘s’ is not the

same with ‘S’.4. The underscore symbol (_) is considered as a

letter in C. It is not recommended to be used, however, as the first character in a name.

5. At least the first 3 characters of a name are significant.

Page 11: Es202 Lecture Notes

Variables, Data Types and Constants

Names... Example

CANNOT start with a number 2iCAN contain a number elsewhere h2oCANNOT contain any arithmetic operators... r*s+tCANNOT contain any other punctuation marks... #@x%£!!a

CAN contain or begin with an underscore _height_CANNOT be a C keyword structCANNOT contain a space im

stupidCAN be of mixed cases Squared

Page 12: Es202 Lecture Notes

Table 2-2 Examples of Valid and Invalid Names

Page 13: Es202 Lecture Notes

An identifier must start with a letter or underscore: it may not have a space or a hyphen.

NoteNote

Page 14: Es202 Lecture Notes

C is a case-sensitive language.

NoteNote

Page 15: Es202 Lecture Notes

Variables, Data Types and Constants

Variables - are like containers in your computer's memory - you can store values in them and retrieve or modify them when necessary. - associated with a memory cell whose value can change as the program executes.

Variable declaration – statements that communicate to the C compiler the names of all variables used in the program and the kind of information stored in each variable.- also tells how that information will be represented in memory.

Page 16: Es202 Lecture Notes

Variables, Data Types and Constants

Syntax for Declarations:

data type variable_list;

Ex. int x,age;float sum,a,b;char middle_intial;

Page 17: Es202 Lecture Notes

When a variable is defined, it is not initialized. We must initialize any variable requiring prescribed data when the function starts.

NoteNote

Page 18: Es202 Lecture Notes

Variables, Data Types and Constants

Data Type – a set of values and a set of operations that can be performed on those values.

Standard Predefined Data Type in C:chardouble int

Page 19: Es202 Lecture Notes

FIGURE 2-6 Nested Block Comments Are Invalid

Page 20: Es202 Lecture Notes

Variables, Data Types and Constants

Seven Basic C Data Types:1. Text (data type char) – made up of single characters

(example x,#,9,E) and strings (“Hello”), usually 8 bits, or 1 byte with the range of 0 to 255.

2. Integer values – those numbers you learned to count with.

3. Floating-point values – numbers that have fractional portions such as 12.345, and exponents 1.2e+22.

4. Double-floating point values – have extended range of 1.7e-308 to 1.7e+308.

5. Enumerated data types – allow for user-defined data types.

6. void – signifies values that occupy 0 bit and have no value. You can also use this type to create generic pointers.

7. Pointer – does not hold information as do the other data types. Instead, each pointer contains the address of the memory location.

Page 21: Es202 Lecture Notes

Variables, Data Types and Constants

int - data typeint is used to define integer numbers.

Ex.{ int Count;

Count = 5; }

float - data typefloat is used to define floating point numbers. Ex.{ float Miles; Miles = 5.6; }

Page 22: Es202 Lecture Notes

Table 2-3 Typical Integer Sizes and Values for Signed Integers

Page 23: Es202 Lecture Notes

FIGURE 2-10 Floating-point Types

Page 24: Es202 Lecture Notes

Variables, Data Types and Constants

double - data typedouble is used to define BIG floating point

numbers. It reserves twice the storage for the number. On PCs this is likely to be 8 bytes.

Ex.{ double Atoms; Atoms = 2500000; }

char - data typechar defines characters. Ex.{ char Letter; Letter = 'x'; }

Page 25: Es202 Lecture Notes

Variables, Data Types and Constants

Modifiers

The three data types above have the following modifiers.

short long signed unsigned The modifiers define the amount of storage

allocated to the variable. The amount of storage allocated is not cast in stone. ANSI has the following rules:

short int <= int <= long int float <= double <= long double

Page 26: Es202 Lecture Notes

Variables, Data Types and Constants

Type Bytes Bits Range short int 2 16 -32,768 -> +32,767 (32kb) unsigned short int 2 16 0 -> +65,535 (64Kb) unsigned int 4 32 0 -> +4,294,967,295 ( 4Gb) int 4 32 -2,147,483,648 -> +2,147,483,647

(2Gb) long int 4 32 -2,147,483,648 -> +2,147,483,647

(2Gb) signed char 1 8 -128 -> +127 unsigned char 1 8 0 -> +255 float 4 32 double 8 64 long double 12 96

Page 27: Es202 Lecture Notes

Variables, Data Types and Constants

Constants – identifiers that are having a constant value all throughout the program execution.- also fixed values that may not be altered by the program.

Examples:1. Character constants – enclosed between

single quotes. Ex. ‘A’, ‘+’2. Integer constants – specified as numbers

without fractional components. Ex. 5 and -160

Page 28: Es202 Lecture Notes

Variables, Data Types and Constants

Floating constants – require the use of decimal point followed by the number’s fractional components. Ex. 16.234

String constants – set of characters enclosed by double quotes. Ex. “bag” and “this is good”

Backslash character constants – enclosing all character constants in single quotes that works for most printing characters. Ex. g = ‘\t’

Page 29: Es202 Lecture Notes

Variables, Data Types and Constants

SEQUENCE NAME MEANING

\a Alert Sound a beep

\b Backspace Backs up one character

\f Form feed Starts a new screen of page

\n New line Moves to the beginning of the next line

\r Carriage Return Moves to the beginning of the current line

\t Horizontal tab Moves to the next Tab position

\v Vertical tab Moves down a fixed amount

\\ Backslash Displays an actual backslash

\’ Single quote Displays an actual single quote

\? Question mark Displays an actual question mark

\”” Double quote Displays an actual double quote

Page 30: Es202 Lecture Notes

Variables, Data Types and Constants

Defining Constants

#define preprocessor- allows us to define symbolic names and constants.

A quick example: #define PI 3.14159

This statement will translate every occurrence of PI in the program to 3.14159.

Here is a more complete example: #define PI 3.14159 main() { int r=10; float cir; cir = PI

* (r*r); }

Page 31: Es202 Lecture Notes

Variables, Data Types and Constants

Defining Constants

The const keyword.- used to create a read only variable. Once initialized, the value of the variable cannot be changed but can be used just like any other variable.

const syntax:main() { const float pi = 3.14; } The const keyword is used as a qualifier to the following

data types - int float char double struct. const int degrees = 360; const float pi = 3.14; const char quit = 'q';

Page 32: Es202 Lecture Notes

Operators

Assignment Operator – Equal sign (=)- the most basic assignment operator where the value on the right of the equal sign is assigned to the variable on the left.

Example:c = c + 1; radius = 2 * diameter;stat = getch();

Page 33: Es202 Lecture Notes

Operators

Binary Operators- take two operands and return a result.

Operator Use Result + op1 + op2 adds op1 to op2 - op1 - op2 subtracts op2 from op1 * op1 * op2 multiplies op1 by op2 / op1 / op2 divides op1 by op2 % op1 % op2 computes the remainder

from dividing op1 by op2

Page 34: Es202 Lecture Notes

Operators

Unary Operators- changes the sign of a value or

variable.- Unary minus (-) and unary plus (+)Examples:

2 +-3((-x) + (+y))

Page 35: Es202 Lecture Notes

Operators

Increment (++) and Decrement (--) Operators

++ increment adds one to a value of the variable

-- decrement subtracts one from a value of the variable

Note: The value of the expression in which ++ or -- operator is used depends on the position of the operator.

Page 36: Es202 Lecture Notes

Increment (++) and Decrement(--) Operators

Prefix increment is when the ++ is placed immediately

in front of its operand.the value of the expression is the

variable’s value after incrementing.

Page 37: Es202 Lecture Notes

Increment (++) and Decrement(--) Operators

Postfix incrementis when the expression’s value is the

value of the variable before it is incremented.

Page 38: Es202 Lecture Notes

Increment (++) and Decrement(--) Operators

Comparison of POSTFIX and PREFIX Increments

Before… x y

5 ?

Page 39: Es202 Lecture Notes

Increment (++) and Decrement(--) Operators

Increments… y = ++x y = x++

Prefix: Increment x and then used it.Postfix: Use x and then increment it.

Prefix PostfixAfter… x y x y

5 6 5 5

Page 40: Es202 Lecture Notes

Examplemain(){int a=3, b;clrscr();b=a++;printf(“b is %d, and a is %d\n”, b, a);b=++a;printf(“Now b is %d, and a is %d\n”, b, a);b=5%--a;printf(“Now b is %d, and a is %d\n”, b, a);printf(“Now b is %d, and a is %d\n”, ++b, a--);printf(“Now b is %d, and a is %d\n”, b, a);}

Page 41: Es202 Lecture Notes

Output

b is 3, and a is 4Now b is 5, and a is 5Now b is 1, and a is 4Now b is 2, and a is 4Now b is 2, and a is 3

Page 42: Es202 Lecture Notes

Operators

Prefix increment/decrement - when the ++ or -- is placed immediately in front of its operand. Meaning the value of the expression is the variables value after incrementing or decrementing.

Postfix increment/decrement – when the ++ or -- comes immediately after the operand. The value of the expression is the value of the variable before it is incremented or decremented.

Page 43: Es202 Lecture Notes

Predefined Mathematical Functions

Function Purposeabs(x) returns the absolute value of integer

x.x=abs(-5); x=5

fabs(x) returns the absolute valued of type double.x=fabs(-5.2); x=5.2

ceil(x) rounds up or returns the smallest whole number that is not less than x.

x=ceil(5.2); x=6floor(x) rounds down or returns the largest

whole number that is not greater than x.x=floor(5.2); x=5

Page 44: Es202 Lecture Notes

Predefined Mathematical Functions

Function Purposesqrt(x) returns the non-negative square of x.

x=sqrt(25); x=5pow(x) returns x to the power of y.

x=pow(4,2); x=16 sin(x) returns the sine of angle x.cos(x) returns the cosine of angle x.tan(x) returns the tangent of angle x.log(x) returns the natural logarithm of x.log10(x) returns the base 10 logarithm of x.

Page 45: Es202 Lecture Notes

Conversion Specifications

Date Types printf conversion specification

scanf conversion specifications

long double %Lf %Lf

double %f %lf

float %f %f

unsigned long int %lu %lu

long int %ld %ld

unsigned int %u %u

int %d %d

short %hd %hd

char %c %c

String - %s

Page 46: Es202 Lecture Notes

I/O Functions

Numeric Input Command

scanf() – one of the Turbo C object stream object that is used to accept data from the standard input, usually the keyboard.

syntax:scanf(“format”, &var_name);

Example:printf(“Input side of the square:”);scanf(“%d”, &s);

Page 47: Es202 Lecture Notes

A terminal keyboard and monitor can be associated only with a text stream. A keyboard is a source

for a text stream; a monitor is a destination for a text stream.

NoteNote

Page 48: Es202 Lecture Notes

FIGURE 2-15 Stream Physical Devices

Page 49: Es202 Lecture Notes

scanf requires variable addresses in the address list.

NoteNote

Page 50: Es202 Lecture Notes

I/O Functions

Character/String Input Command

getch() – allows the user to input a character and wait for the enter key. Inputted char will not be echoed but could be stored if location is specified.

Syntax:getch();var_name = getch();

Example: ans = getch();

Page 51: Es202 Lecture Notes

I/O Functions

Character/String Input Command

getche() – allows the user to input a character and there is no need for the enter key. Inputted char will be echoed but could be stored if location is specified.

Syntax:getche();var_name = getche();

Example: ans = getche();

Page 52: Es202 Lecture Notes

I/O Functions

Character/String Input Command

gets() – allows the user to input a sequence of characters (string).

syntax:gets(variable_name_of_char_type);

Example:gets(name);

Page 53: Es202 Lecture Notes

I/O Functions

Output Command

printf – writes formatted output to the standard output device such as the monitor.

syntax:printf(“format code”,var_name);

Example:printf(“%d”,x);

puts – writes the string to the standard output device such as the monitor and positions the cursor to the next line.

syntax:puts(“string expression”);

Example: puts(“CIT”);

Page 54: Es202 Lecture Notes

FIGURE 2-17 Output Stream Formatting Example

Page 55: Es202 Lecture Notes

I/O Functions

Output Command

putchar – writes the single character to the screen.

syntax:putchar(var_name);

Example:putchar(a);

Page 56: Es202 Lecture Notes

Introduction to C Programming

CONTINUECONTROL FLOW

Page 57: Es202 Lecture Notes

Control Flow

Control Structures - specify the sequence of execution of a group of statements.

3 Types:1. Sequential2. Conditional3. Iterative

Sequential - organized such that statements are executed in sequence, i.e., one after the other in the order of their appearance in the source code.

Page 58: Es202 Lecture Notes

Sample Problem 6

Make a flowchart that will input an integer. If the integer is negative determine the square of that integer and print, otherwise just print the inputted integer.

Page 59: Es202 Lecture Notes

Sample Problem

7. Make a flowchart that will compute for the area of a triangle whose base = 5 and height = 12. Output the computed area.

8. Make a flowchart that will input a degree in centigrade and will output degree in fahrenheight.

9.Make a flowchart that will input 2 integers. Determine the sum, if the sum is greater than or equal to 20 then output the second integer, otherwise, output the first integer.

Page 60: Es202 Lecture Notes

Problem 10

At the University of Palompon, every unit is worth P475 in enrollment fees. An additional 15% of the TUITION FEE is paid as miscellaneous fee. Make a flowchart that will input the number of UNITS a student is enrolled and output the TOTAL TUTION FEE to be paid.

Page 61: Es202 Lecture Notes

Problem 11

Any customer whose total PURCHASE is at least P1000 will be given a 10% discount. Make a flowchart that would input the customer’s PURCHASE and output his net BILL.

Page 62: Es202 Lecture Notes

Problem 12

Make a flowchart that will input the monthly salary of Pedro and will output his annual salary and tax due. Compute his tax to be paid based on the ff: rules: if the annual salary is greater than or equal to P60,000 the tax due is 15% of the annual salary otherwise the tax due is 5% of the annual salary.

Page 63: Es202 Lecture Notes

Problem 13

A taxi charges P10.50 for the first 300 meters and P5.50 for every 200 meters thereafter. Any distance covering the next 200 meter zone is still charged P5.50. Make a program that would input the DISTANCE a trip took and output the FEE.

Page 64: Es202 Lecture Notes

Problem 14

Every leap year is divisible by 4. However, if a year is divisible by 100, it must also be divisible by 400 for it to be a leap year. Hence, 2000 is a leap year, but 1900 is not. Make a flowchart that will input a value for YEAR (integer) and output whether it is a “LEAP YEAR” or “NOT A LEAP YEAR”.

Page 65: Es202 Lecture Notes

Make a c program to input 2 integers and perform the ff:

1> ADD

2> SUBTRACT

3> MULTIPLY

4> DIVIDE

If the input is not within the choices then it will display WRONG INPUT.

Page 66: Es202 Lecture Notes

Leap Year Problem

Q: Is the year 2000 a leap year? A: Yes, because the rule is: in the

Gregorian calendar, leap years occur in years exactly divisible by four, except that years ending in 00 are leap years only if they are divisible by 400.

So, 1700, 1800, 1900, 2100, and 2200 are not leap years. But 1600, 2000, and 2400 are leap years.

Page 67: Es202 Lecture Notes
Page 68: Es202 Lecture Notes

Begin

Are the last two digits of the

year 00?

Is the yeardivisible by

400?

The year is aleap year

The year is anot leap year

Is the yeardivisible by

4?

The year is aleap year

The year is anot leap year

End

Yes

YesYesNo

No

No

Page 69: Es202 Lecture Notes

main() { int year; printf("Enter a year(ex: 2005):"); scanf("%d", &year); if(year%4==0) { if(year%100==0) { if(year%400==0) printf("The year %d is a LEAP YEAR", year); else printf("The year %d is NOT A LEAP YEAR", year); } else printf("The year %d is a LEAP YEAR", year); } else printf("The year %d is NOT A LEAP YEAR", year); getch(); }

Page 70: Es202 Lecture Notes

Problem 14

Make a flowchart that will input 10 integers. Output the sum of the inputted integers. Lots of input and not good to see. What if we have hundreds, thousands or even millions of inputs? How to solve this problem?

Page 71: Es202 Lecture Notes

Control Flow

Conditional Control Structure - organized in such a way that there is always a condition that has to be evaluated first. The condition will either evaluate to a true or false.

2 Types:1. if statement (including if-else and nested if)2. switch case statement

Page 72: Es202 Lecture Notes

Operators

Conditional Operators- expressions that evaluates to true or false.

Operator Use Result > op1 > op2 true if op1 is greater than op2 >= op1 >= op2 true if op1 is greater or equal

to op2 < op1 < op2 true if op1 is less than op2 <= op1 <= op2 true if op1 is less or equal to

than op2 == op1 == op2 true if op1 is equal to op2 != op1 != op2 true if op1 is not equal to

op2

Page 73: Es202 Lecture Notes

Operators

Logical Operators- used in boolean expressions and consists of logical “and", “or" and “not".

0-> false and 1-> true or nonzero digit

Operator Use Result && op1 && op2 true if op1 and op2 are both

true || op1 || op2 true if either op1 or op2 is

true ! !op1 op1 is false if its original

value is true and vice versa

Page 74: Es202 Lecture Notes

Control Flow

if Selection Structure- performs an indicated action only when the condition is true, otherwise the action is skipped.

Syntax: if (<expression>)<statement>

Condition

StatementT

Page 75: Es202 Lecture Notes

Example:Write a program that will allow the user to input an

integer value. If the value is greater than or equal to zero, print the word “POSITIVE”.

Begin

End

num

if num>=0

“POSITIVE”

Page 76: Es202 Lecture Notes

Control Flow

Other Problems:1. Write a program that will allow the user

to input a number. Print the word NEGATIVE if the number is a negative value.

2. Write a program to input two integers. Thereafter, the program should determine if these two numbers are equivalent. If they are equivalent, print the word EQUIVALENT.

3. Write a program that will input an integer and determine if it is an even number.

Page 77: Es202 Lecture Notes

Control Flow

if-else Selection Structure

- allows the programmer to specify that different actions are to be performed when the condition is true than when the condition is false.

- If condition evaluates to true, then statementT is executed and statementF is skipped; otherwise, statementT is skipped and statementF is executed.

Page 78: Es202 Lecture Notes

Control Flow

Syntax:

if (condition)

statementT;

else

statementF;

Condition

StatementT

Statement

F

Page 79: Es202 Lecture Notes

Good Programming Practice

Indent both body statements of an if...else statement.

If there are several levels of indentation, each level should be indented the same additional amount of space.

Page 80: Es202 Lecture Notes

Control Flow

Problems:1. Write a program that will allow the user to input

a number. Print the word NEGATIVE if the number is a negative value otherwise print POSITIVE if the number is positive.

2. Write a program to input two integers. Thereafter, the program should determine if these two numbers are equivalent. If they are equivalent, print the word EQUIVALENT otherwise print the word NOT EQUIVALENT.

3. Write a program that will input an integer and determine if it is an even or odd number.

Page 81: Es202 Lecture Notes

Control Flow

if-else (multiple alternatives)- The conditions in a multiple-alternative decision are evaluated in sequence until a true condition is reached. If a condition is true, the statement following it is executed, and the rest of the multiple-alternative decision is skipped. If a condition is false, the statement following it is skipped, and the condition next is tested. If all conditions are false, then the statement following the final else is executed.

Page 82: Es202 Lecture Notes

Condition

Statement

Condition

Condition

Statement

Statement

Statement

T

T

T

F

F

F

Control Flow

Syntax:if (condition)

statement;else if (condition)

statement;else if (condition)

statement;else

statement;

Page 83: Es202 Lecture Notes

Control Flow

Example:

Make a C program that will accept a score and display based on the following conditions:

Score Display86 – 100 (inclusive) Very Good75 – 85 (inclusive) FairBelow 75 Failed

Page 84: Es202 Lecture Notes

Control Flow

Nested-if StatementSyntax:

if (condition){if (condition)

statement;else

statement;}

Page 85: Es202 Lecture Notes

Good Programming Practice

A nested if...else statement can perform much faster than a series of single-selection if statements because of the possibility of early exit after one of the conditions is satisfied.

In a nested if...else statement, test the conditions that are more likely to be true at the beginning of the nested if...else statement. This will enable the nested if...else statement to run faster and exit earlier than testing infrequently occurring cases first.

Page 86: Es202 Lecture Notes

Good Programming Practice

Always putting the braces in an if...else statement (or any control statement) helps prevent their accidental omission, especially when adding statements to an if or else clause at a later time. To avoid omitting one or both of the braces, some programmers prefer to type the beginning and ending braces of blocks even before typing the individual statements within the braces.

Page 87: Es202 Lecture Notes

Common Programming Error

Forgetting one or both of the braces that delimit a block can lead to syntax errors or logic errors in a program.

Page 88: Es202 Lecture Notes

Placing a semicolon after the condition in an if statement leads to a logic error in single-selection if statements and a syntax error in double-selection if...else statements (when the if part contains an actual body statement).

Common Programming Error

Page 89: Es202 Lecture Notes

Control Flow

Example

Make a C program to input an integer. Output the integer if it is a positive even integer.

Page 90: Es202 Lecture Notes

Control Flow

Leap years occur in years exactly divisible by four, except that years ending in 00 are leap years only if they are divisible by 400. Hence, 2000 is a leap year, but 1900 is not. Make a flowchart that will input a value for YEAR (integer) and output whether it is a “LEAP YEAR” or “NOT A LEAP YEAR”.

Page 91: Es202 Lecture Notes

Control Flow

Switch Statement

Is a selection statement provided by C. It has a built in multiple branch and work similar to if else ladder generally.

Page 92: Es202 Lecture Notes

Control Flow

Switch Statement- the controlling expression, an expression with a value of type int or type char, is evaluated and compared to each of the case labels in the case constant until a match is found. A case constant is made of one or more labels of the form case followed by a constant value and a colon.

Page 93: Es202 Lecture Notes

Control Flow

When a match between the value of the controlling expression and a case label value is found, the statement following the case label are executed until a break statement is encountered. Then the rest of the switch statement is skipped. A default case is allowed which will be executed if no other statement match is found.

Page 94: Es202 Lecture Notes

Control Flow

It is defined by C that a complier must support a minimum of 257 case statements in C89 and 1023 case statements in C99 though you may want to keep this to minimum in consideration of efficiency.

Page 95: Es202 Lecture Notes

Control Flow

Switch StatementSyntax:

switch (controlling expression){case constant: statement;

break;case constant: statement;

break;. . .

default: statement;}

Page 96: Es202 Lecture Notes

Control Flow

Break

- exits from the lowest-level loop in which it occurs.

- used for early exit from the loop, or for exiting a forever loop

Page 97: Es202 Lecture Notes

Control Flow

Continue – causes immediate loop iteration,

skipping the rest of the loop statements

- jumps to the loop test when used with while or do

- jumps to loop increment, then test when used with for

- does not exit the loop (unless next loop is false)

Page 98: Es202 Lecture Notes

BREAK and CONTINUE

You can exit out of a loop at any time using the break statement. This is useful when you want a loop to stop running because a condition has been met other than the loop end condition.

#include<stdio.h>

int main(){ int i; while (i < 10){ i++; if (i == 5) break;}return 0;}

Page 99: Es202 Lecture Notes

Control Flow

Example

Make a C program that prompts the user to input 2 integers and will perform the following operations:

Choice Operation 1 ADDITION

2 SUBTRACTION 3 MULTIPLICATION

Page 100: Es202 Lecture Notes

Solution#include<stdio.h>#include<conio.h>

main(){ int num1, num2, sum, diff, prod, choice; printf("Enter the first number:"); scanf("%d", &num1); printf("Enter the second number:"); scanf("%d", &num2); printf("Enter your choice (1-> ADD, 2-> SUBTRACT, 3->MULTIPLY:"); scanf("%d", &choice); switch(choice) { case 1: {

sum=num1+num2; printf("The sum of 2 numbers is %d", sum); break; }

case 2: { diff=num1-num2; printf("The difference between 2 numbers is %d", diff); break; }

case 3: { prod=num1*num2; printf("The product of 2 numbers is %d", prod);

break; } default: printf("Wrong Choice!!!"); } getch(); }

Page 101: Es202 Lecture Notes

Problem 14

Make a flowchart that will input 10 integers. Output the sum of the inputted integers. Lots of input and not good to see. What if we have hundreds, thousands or even millions of inputs? How to solve this problem?

Page 102: Es202 Lecture Notes

Solution: Use Loops

When is loop required?

Repeating Statement Execution

Loop is a sequence of instructions that is continually repeated until a certain condition is reached.

It is used to repeat execution of block of code.

Page 103: Es202 Lecture Notes

Execution of Loops

Typically this is done inside a loop statement of some sort using a variable as a counter to keep track of which character is to be checked. The counter variable may be incremented by one, each time through, so that the first element is examined the first time through the loop, the second element the second time, and so forth.

Page 104: Es202 Lecture Notes

Execution of Loops

Being able to repeatedly execute a statement or compound statement is an essential feature of programming.

Page 105: Es202 Lecture Notes

Introduction to Loops

What is the difference between a while and a do / while loop?

What is a sentinel value?How do you pick a good sentinel

value?Would you ever intentionally want an

infinite loop?Why shouldn’t you generally use

floats or doubles as control variables in loops?

Page 106: Es202 Lecture Notes

Loops

There are several loop types.

Depending on situation, sometimes it is better to use one kind of loop than another, but every loop can be transformed into one another.

Page 107: Es202 Lecture Notes

Loops

This is not so important for beginners, you just need to know that there is good and better use of particular loop.

Page 108: Es202 Lecture Notes

Control FlowA loop has the following components:

1.Initialization of variables – setting an initial value of zero before the loop statement is reached.

2.Condition/testing – (that would evaluate to either true or false) the condition to check is usually made on the current value of the variable initialized in (1) for it controls the loop repetition.

3.Body – statements that are repeated in the loop.4.Updating – a statement inside the body of the

loop that updates the value of the variable that is initialized during each repetition.

Page 109: Es202 Lecture Notes

Control Flow

3 Types:

1. do-while statement2. while statement3. for statement

Page 110: Es202 Lecture Notes

Control Flow

do-while statement

- This loop executes a block of codes as long as the specified condition is true.- It is a post checked loop because it checks the controlling condition after the code is executed.

Page 111: Es202 Lecture Notes

Control FlowSyntax:

do{

statement/s;} while (loop repetition condition);

Example:c=1;do{printf(“Hello World\n”);c++;} while (c<=5);

Page 112: Es202 Lecture Notes

Control Flow

while statement

- Like do-while, this will execute a block of codes while the given condition is true. - It is a pre-checked loop because it checks the controlling condition first before the code is executed.

Page 113: Es202 Lecture Notes

Control FlowSyntax:

while (loop repetition condition){

statement/s;}

Example:c=1;while (c<=5){

printf(“Hello World\n”);c++;

}

Page 114: Es202 Lecture Notes

Control Flow

for statement- a kind of loop command wherein the execution of the statement does not depend on another instruction.

Syntax:for (initialization expression; loop repetition

condition; update expression){

statement/s;}

Page 115: Es202 Lecture Notes

Control Flow

Example

for (c=1; c<=5; c++)printf(“Hello World\n”);

Page 116: Es202 Lecture Notes

116

Loop types (reminder)

Indefinite Loop:

You do not know ahead of time how many times your loop will execute.

For example, you do not know how many books a person might order.

Definite Loop:

You know exactly how many times you want the loop to execute.

not at compile time necessarily

Page 117: Es202 Lecture Notes

117

Infinite Loop

You can still end up with an infinite loop when using for loops

for (counter = 0; counter <= 10; counter--)

Page 118: Es202 Lecture Notes

Types of Loop

The following are the different types of Loops

Page 119: Es202 Lecture Notes

119

Basic For Loop Syntax

For loops are usually used when we know exactly how many times we need to execute repeating block of code. It is also good for creating definite loops.

int counter;

for (counter =1;counter <= 10;counter++)

System.out.println (counter);

1. Priming: Set 1. Priming: Set the start value.the start value.

2. Test 2. Test Condition: Set Condition: Set the stop value.the stop value.

3. Update: Update the 3. Update: Update the value.value.

Note that each section Note that each section is separated by a is separated by a semicolon.semicolon.

Page 120: Es202 Lecture Notes

120

for Loop Flowchart

1. Priming1. Priming

Set counter=1Set counter=1

2. Test2. Test

counter counter

<= 10<= 10

3a. print counter3a. print counter

3b. Update counter++;3b. Update counter++;

TRUETRUE

FALSEFALSE

Page 121: Es202 Lecture Notes

121

For Loop Variations

The limit can be a variable:for ( i = 1; i <= limit; i++)This counts from 1 to limit

Update may be negative:

for (i = 100; i >= 1; i--)This counts from 100 to 1.

Update may be greater than 1:for (i = 100; i >= 5; i -= 5)This counts from 100 to 5 in steps of 5

Page 122: Es202 Lecture Notes

While LoopWhile loop is usually used when we do not know

exactly how many times we need to execute repeating block of code

while (*){/* repeating block of code */} * Is a condition which is true or false. Ex.

Value> 5Condition is checked at every iteration start.

If condition is true, execution will continue, if it is false execution will break.

Page 123: Es202 Lecture Notes

Do While

Do-while loop is usually used when we do not know exactly how many times we need to execute repeating block of code, but we know that we need to execute it at least once.

do {/* repeating block of code */} while (*);

do-while is same as while loop with difference that the condition is checked at every iteration end. Consequence is that repeating block of code in do-while loop is always executed at least once.

Page 124: Es202 Lecture Notes

Example

1. Make a flowchart that will input 10 integers. Output the sum of the inputted integers.

2. Make a C rogram that will input 20 scores of students. Output the average of the scores.

3. Make a C program to input 20 integers. Output the average of all positive odd integers.

Page 125: Es202 Lecture Notes

Additional Examples

4. Make a C program that will input integers, positive and negative. The flowchart/program will terminate if a negative number is inputted. Output the average of all positive integers inputted.

5. Make a C program to input 10 integers. Output the biggest integer

Page 126: Es202 Lecture Notes

6. Make a C program that will prompts the user to input an integer. Output if the inputted integer is PRIME or COMPOSITE

Page 127: Es202 Lecture Notes

Additional Examples

6. Make a C program to input N number of integers. Output the average of all

positive odd integers.

Modify your program so that every time you run, it will prompt the user to continue or not. If you press Y it will run again, otherwise if you press any key it terminates.

Page 128: Es202 Lecture Notes

Additional Examples

1. Make a C program to input 5 names of student. Each student has 3 exam scores. Determine the average exam score of each student.

2. Make a C program to input 10 names of student. Each student has 3 exam scores. Determine the average exam score of each student. Output the highest average exam score.

Page 129: Es202 Lecture Notes

Make a C program that will all PRIME integers from 1 to 1000.

Page 130: Es202 Lecture Notes

NESTED LOOPS

The for loop and all other repetition constructs can also be nested to any degree. In a simple word, nesting means loop in loop.

Page 131: Es202 Lecture Notes

NESTED LOOPS

The OUTER loop is executed until the condition become FALSE. For every row value (OUTER LOOP), the INNER loop will be executed until the condition become FALSE. In simple word, the external loop will be for the row and the internal for loop will be the column.

Page 132: Es202 Lecture Notes

NESTED LOOPS

Page 133: Es202 Lecture Notes

NESTED LOOPS

Nested loops is the most basic way a matrix can be manipulated.

Page 134: Es202 Lecture Notes

Array

The C language provides a capability that enables the user to define a set of ordered data items known as an array.

Suppose we had a set of grades that we wished to read into the computer and suppose we wished to perform some operations on these grades, we will quickly realize that we cannot perform such an operation until each and every grade has been entered since it would be quite a tedious task to declare each and every student grade as a variable especially since there may be a very large number.

Page 135: Es202 Lecture Notes

Array

In C we can define variable called grades, which represents not a single value of grade but a entire set of grades. Each element of the set can then be referenced by means of a number called as index number or subscript.

Page 136: Es202 Lecture Notes

Arrays

Array –is a collection of same type elements under the same variable identifier referenced by index number.

Arrays are widely used within programming for different purposes such as sorting, searching and etc.

Page 137: Es202 Lecture Notes

Arrays

Syntax of Array Declaration:Data_type array_name[size];

Where:data_type – valid data typearray_name – any user-defined identifiersize – number of elements in the array

Example: int num[5];

Page 138: Es202 Lecture Notes

ARRAYa data structure which hold multiple variables of the same data type.

IN SHORT, ARRAY IS–Structures of related data items–Static entity – same size throughout program

To refer to an element, specify–Array name–Position number

Page 139: Es202 Lecture Notes

Format:arrayname[ position number ]

–First element at position 0 (must always be put in mind)

Example: n element array named c:

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

Page 140: Es202 Lecture Notes

Arrays

-45

2

4

72

1

num[0]

num[1]

num[2]

num[3]

num[4]

Subscript – the position number contained within square brackets.

- must be an integer or an integer expression.

Page 141: Es202 Lecture Notes

Arrays

Types of Array

1.Single Dimensional

1.Multidimensional

Page 142: Es202 Lecture Notes

Initialization of Array

We can initialize the elements in the array in the same way as the ordinary variables when they are declared.

The general form of initialization of arrays

type array_name[size]={list of values}; The values in the list care separated by commas, for example the statement

Page 143: Es202 Lecture Notes

Initialization of Array

int number[3]={0,0,0};

Will declare the array size as an array of size 3 and will assign zero to each element. If the number of values in the list is less than the number of elements, then only that many elements are initialized. The remaining elements will be set to zero automatically.

Page 144: Es202 Lecture Notes

Initialization of Array

In the declaration of an array the size may be omitted, in such cases the compiler allocates enough space for all initialized elements. For example the statement,

int counter[]={1,1,1,1};

Will declare the array to contain four elements with initial values 1. this approach works fine as long as we initialize every element in the array.

Page 145: Es202 Lecture Notes

Initialization of Array

Initializing an array

Using the for loop:int n [ 10 ] , i ;for (i = 0; i < 10; i ++)

n [ i ] = 0 ;

The initialization above is the same as:

int n [ 10 ] = { 0 } ;

Page 146: Es202 Lecture Notes

Initialization of Array

Storing String in Character Arrays

Ex: char string1[] = “first”; orchar string1[] = { ‘f’ , ’i’ , ’r’ , ’s’ , ’t’ , ’\

0’ };orscanf(“%s”, string1);printf(“%s”, string1);

Page 147: Es202 Lecture Notes

Initialization of Array

Multi dimensional Arrays

Often there is a need to store and manipulate two dimensional data structure such as matrices & tables. Here the array has two subscripts. One subscript denotes the row & the other the column.

data_type array_name[row_size][column_size];

int m[10][20]

Here m is declared as a matrix having 10 rows( numbered from 0 to 9) and 20 columns(numbered 0 through 19). The first element of the matrix is m[0][0] and the last row last column is m[9][19]

Page 148: Es202 Lecture Notes

Initialization of Array

Elements of multi dimension arrays:

A 2 dimensional array marks [2][2] is shown. The first element is given by marks [0][0] contains 90 & second element is marks [0][1] and contains 75 and so on.

marks [0][0]

90

marks [0][1]

75

marks [1][0]

85

marks [1][1]

67

Page 149: Es202 Lecture Notes

Initialization of Array

Like the one dimension arrays, 2 dimension arrays may be initialized by following their declaration with a list of initial values enclosed in braces

Example:

int table[2][3]={0,0,0,1,1,1};

Initializes the elements of first row to zero and second row to 1. The initialization is done row by row. The above statement can be equivalently written as

int table[2][3]={{0,0,0},{1,1,1}}

Page 150: Es202 Lecture Notes

Array elements are like normal variables

c[ 0 ] = 3;printf( "%d", c[ 0 ] );

Perform operations in subscript. If x equals 3

c[ 5 - 2 ] == c[ 3 ] == c[ x ]

Page 151: Es202 Lecture Notes

Declaring multiple arrays of same type

Format similar to regular variables

Example:

int b[ 100 ], x[ 27 ];

Page 152: Es202 Lecture Notes

Points to Ponder

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

If not enough initializers, rightmost elements become 0int n[ 5 ] = { 0 } All elements 0•If too many a syntax error is produced syntax error•C arrays have no bounds checking

If size omitted, initializers determine it

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

5 initializers, therefore 5 element array

Page 153: Es202 Lecture Notes

Example

Make a C program to create an array of 5 numbers. Output the numbers.

Solution:

Page 154: Es202 Lecture Notes

Solution

#include <stdio.h>

main(){ int x, num[5];

for(x=0; x<=5; x++) { printf("Enter a number%d:",x); scanf("%d", &num[x]); }

for(x=0; x<=5; x++) { printf("The content of num[%d] is %d\n",x, num[x]); } getch();}

Page 155: Es202 Lecture Notes

Example

#include <stdio.h>#include <conio.h>main(){ char word[20];

word[0]='H'; word[1]='e'; word[2]='l'; word[3]='l'; word[4]='o'; word[5]=‘\0’; //slash zero printf("The contents of word[] is --> %s\n", word);

getch();}

Page 156: Es202 Lecture Notes

Example

#include <stdio.h>

main(){ int x, num[5];

num[0]=1; num[1]=2; num[2]=3; num[3]=4; num[4]=5; num[5]=0; for(x=0; x<=5; x++) { printf("The contents of num[%d] is --> %d\n",x,

num[x]); }getch();}

Page 157: Es202 Lecture Notes

Problem

Make a C program to create an array of 5 names. Output the names.

Solution:

Page 158: Es202 Lecture Notes

Solution #include<stdio.h> #include<conio.h> #include<string.h>

main() { int x; char name[5][15]; fflush(stdin); for(x=0; x<5; x++) { fflush(stdin); printf("Enter name%d:", x); gets(name[x]); } fflush(stdin); for(x=0; x<5; x++) { fflush(stdin); printf("Name is %s", name[x]); printf("\n"); } getch(); }

Page 159: Es202 Lecture Notes

/* Histogram printing program */#include <stdio.h>#define SIZE 10

main(){ int n[ SIZE ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 }; /* Initialize array*/ int i, j;

printf( "%s%13s%17s\n", "Element", "Value", "Histogram" );

for ( i = 0; i <= SIZE - 1; i++ ) { /* Loop*/

printf( "%7d%13d ", i, n[ i ]) ;

for ( j = 1; j <= n[ i ]; j++ ) /* print one bar */ printf( "%c", '*' ); /*Print*/

printf( "\n" ); } /* End of for loop i */

getch();} /* END Main Program */

Page 160: Es202 Lecture Notes

Program Output:

Element Value Histogram 0 19 ******************* 1 3 *** 2 15 *************** 3 7 ******* 4 11 *********** 5 9 ********* 6 13 ************* 7 5 ***** 8 17 ***************** 9 1 *

Page 161: Es202 Lecture Notes

Other Application of Array

The following are the most common applications of array

Page 162: Es202 Lecture Notes

Arrays

Searching ArraysSearching – the process of finding a particular

element of an array.Linear search – compares each element of the

array with the search key.Binary search – locates the middle element and

compares it to the search key. If they are equal, the search key is found and the array subscript is returned. Otherwise, it eliminates one half of the elements in a sorted array after each comparison.

Page 163: Es202 Lecture Notes

Searching ArraysExamples:1. Create an array of N integers.

Determine if 13 is within the array.

2. Create an array of N integers. Input an integer to be searched in the array. Output whether the integer to be searched exist or not.

Page 164: Es202 Lecture Notes

Searching Arrays (Con’t)

3. Create an array of N scores. Determine the average and output all the scores that are greater than or the average scores.

Page 165: Es202 Lecture Notes

Arrays

Sorting ArraysSorting data – placing the data into a

particular order such as ascending or descending.

Example:Write a program that sorts the values in the elements of the 10-element array a into ascending order.

Page 166: Es202 Lecture Notes

MULTI DIMENSIONAL ARRAYS

The arrays we have been using so far are called 1-dimensional arrays because they only have what can be thought of a 1 column of elements. 2-dimensional arrays have rows and columns. Here is a picture which explains it better:

1-dimensional array

0 1

1 2

2 3

Page 167: Es202 Lecture Notes

2-dimensional array

0 1 2

0 1 2 3

1 4 5 6

2 7 8 9

You do get 3-dimensional arrays and more but they are not used as often. Here is an example of how you declare a 2-dimensional array and how to use it. This example uses 2 loops because it has to go through both rows and columns.

int a[3][3],i,j;for (i = 0;i < 3;i++)for (j = 0;j < 3;j++)a[i][j] = 0;

Page 168: Es202 Lecture Notes

What is a Magic Square?

Definition, Special Properties

A magic square is an arrangement of the numbers from 1 to n^2 (n-squared) in an nxn matrix, with each number occurring exactly once, and such that the sum of the entries of any row, any column, or any main diagonal is the same. It is not hard to show that this sum must be n(n^2+1)/2.

Page 169: Es202 Lecture Notes

Magic Square Con’t

The simplest magic square is the 1x1 magic square whose only entry is the number 1.

Page 170: Es202 Lecture Notes

Magic Square Con’t

The next simplest is the 3x3 magic square

Page 171: Es202 Lecture Notes

Method for constructing a magic square of odd order

Starting from the central column of the first row with the number 1, the fundamental movement for filling the squares is diagonally up and right, one step at a time. If a filled square is encountered, one moves vertically down one square instead, then continuing as before. When a move would leave the square, it is wrapped around to the last row or first column, respectively.

Page 172: Es202 Lecture Notes

Method for constructing a magic square of odd order

Complete steps

Page 173: Es202 Lecture Notes

Method for constructing a magic square of odd order

Starting from other squares rather than the central column of the first row is possible, but then only the row and column sums will be identical and result in a magic sum, whereas the diagonal sums will differ. The result will thus be a semi magic square and not a true magic square. Moving in directions other than north east can also result in magic squares.

You can start from any number rather than 1 and continue the same method to derive various patterns of magic squares.

Page 174: Es202 Lecture Notes

Other Application of Multidimensional Array

1.Tic Tac Toe Game2.Number Puzzle Game3.Can you think of other

applications?

Page 175: Es202 Lecture Notes

Functions

The basic philosophy of function is divide and conquer by which a complicated tasks are successively divided into simpler and more manageable tasks which can be easily handled. A program can be divided into smaller subprograms that can be developed and tested successfully.

Page 176: Es202 Lecture Notes

Functions

A function is a complete and independent program which is used (or invoked) by the main program or other subprograms. A subprogram receives values called arguments from a calling program, performs calculations and returns the result to the calling program.

Page 177: Es202 Lecture Notes

FUNCTION

Most of the time, however, unless the function is supposed to do an actual input, we try NOT to put scanf inside. Instead, whatever the function needs as input, we pass it as parameter. The output of the function on the other hand is returned to the user through the return statement. This way, function is a stand-alone function.

Page 178: Es202 Lecture Notes

Usually, we call or invoke this program (function) from our main program: main( )

Since functions take input through parameters, it is important that we need to clearly understand parameter and parameter transmission.

Page 179: Es202 Lecture Notes

Advantages of using functions

1.It facilitates top down modular programming.

2. the length of the source program can be reduced by using functions at appropriate places.

3. It is easy to locate and isolate a faulty function for further investigation.

Page 180: Es202 Lecture Notes

Con’t Advantages…

4. A function may be used by many other programs this means that a c programmer can build on what others have already done, instead of starting over from scratch.

5. A program can be used to avoid rewriting the same sequence of code at two or more locations in a program.

Page 181: Es202 Lecture Notes

Con’t Advantages…

6. Programming teams does a large percentage of programming. If the program is divided into subprograms, each subprogram can be written by one or two team members of the team rather than having the whole team to work on the complex program

Page 182: Es202 Lecture Notes

Why C used Functions ?

1. Many programs require that a specific function is repeated many times instead of writing the function code as many timers as it is required we can write it as a single function and access the same function again and again as many times as it is required.

2. We can avoid writing redundant program code of some instructions again and again.

Page 183: Es202 Lecture Notes

Con’t Why…

3. Programs with using functions are compact & easy to understand. 4. Testing and correcting errors is easy

because errors are localized and corrected.

5. We can understand the flow of program, and its code easily since the readability is enhanced while using the

functions.

6. A single function written in a program can also be used in other programs also.

Page 184: Es202 Lecture Notes

Difference between the main program and the function

Main Program

Input Output

Function

Input Output

scanf() printf() parameters return

Page 185: Es202 Lecture Notes

WHAT ARE PARAMETERS

Parameters serve as a way to communicate information to a function. One use of parameters as stated earlier is to be able to supply input to the function.

You need to declare variables inside the parameter brackets to store the values of the parameters that are passed to the function.

Page 186: Es202 Lecture Notes

2 types of Parameter

Formal Parametersare parameters as they appear in function declarations

Actual Parametersare parameters as they appear in function calls

Page 187: Es202 Lecture Notes

#include <stdio.h> int main (void); int calculate_bill (int, int, int); int main() {

int bill; int fred = 25; int frank = 32; int franny = 27; bill = calculate_bill (fred, frank, franny); printf("The total bill comes to $%d.00.\n", bill); exit (0);

} int calculate_bill (int diner1, int diner2, int diner3) {

int total; total = diner1 + diner2 + diner3; return total; }

Page 188: Es202 Lecture Notes

In the function main in the example above, fred, frank, and franny are all actual parameters when used to call calculate_bill. On the other hand, the corresponding variables in calculate_bill (namely diner1, diner2 and diner3, respectively) are all formal parameters because they appear in a function definition.

Although formal parameters are always variables (which does not mean that they are always variable parameters), actual parameters do not have to be variables. You can use numbers, expressions, or even function calls as actual parameters.

Page 189: Es202 Lecture Notes

Formal and actual parameters

Both the arguments actual and formal should match in number type and order. The values of actual arguments are assigned to formal arguments on a one to one basis starting with the first argument as shown below:

main() { function1(a1,a2,a3……an) }

function1(f1,f2,f3….fn); { function body; }

Page 190: Es202 Lecture Notes

Formal and actual parameters

The number of formal arguments and actual arguments must be matched to each other. Suppose if actual arguments are more than the formal arguments, the extra actual arguments are discarded. If the number of actual arguments are less than the formal arguments then the unmatched formal arguments are initialized to some garbage values. In both cases no error message will be generated.

Page 191: Es202 Lecture Notes

Here is an Add function which adds the 2 parameters together and then returns the result.

#include<stdio.h>

int Add(int a,int b){ return a + b;}

int main(){ int answer; answer = Add(5,7);return 0;}

Page 192: Es202 Lecture Notes

.

2. User / Programmer-defined Function

two types of functions:

e.g. main( ), scanf( ),printf( ), pow( ),

toupper( ), strchr( )

1. Built-in function or Standard Function

Page 193: Es202 Lecture Notes

Types of functions: A function may belong to any one of the following

categories:

1. Functions with no arguments and return values.

1. Functions with no arguments but with return values.

3. Functions with arguments and no return values.

4. Functions with arguments and return values.

Page 194: Es202 Lecture Notes

Syntax: returndata_type functionName (parameter list)

{ <local variable declaration>

statements;return expression;

}

Note: No function can have the same name as the one of TC’s reserved words.

Page 195: Es202 Lecture Notes

where:

returndata_type= specifies the type of data returned by the function

functionName = user-identifier name of the function

Parameter list= specifies a list of data type(s) and variable(s) accepted by the function

return = a statement placed within the function

that simply return the value specified in the expression.

Page 196: Es202 Lecture Notes

Functions Returning Values The return keyword has two important uses:

1. It can be used to cause an immediate exit from the function it is in. That is, the return will cause program execution to return to the calling as soon as it is encountered.

2. It can also be used to return a value.

Note: The return statement can also be used without any value associated with it.

Page 197: Es202 Lecture Notes

When we want a function to simply perform a task, without returning a value, then we can explicitly specify the data type as void before a function name.

By convention C’s parameter passing is call-by-value and call-by-reference

For now, all the examples that we will study here are called-by-value

Page 198: Es202 Lecture Notes

Functions

Example:int func(int one, int two){

int sum;sum=one + two;return sum;

}

Page 199: Es202 Lecture Notes

FunctionsFunction Definition (Without return type and

parameters)Syntax:

void fname(void){

local declarationsexecutable statements

}Example:

void hello(void){printf(“Hello”);

}

Page 200: Es202 Lecture Notes

FunctionsFunction Definition (Without return type and

with parameters)Syntax:

void fname(parameters list){local declarationsexecutable statements

}Example:

void add(int one, int two){int sum;sum=one + two;printf(“Sum=%d”, sum);

}

Page 201: Es202 Lecture Notes

Functions with no arguments and return values

#include<>

statement1( )

{

printf(“\n Sample output”);

return;

}

Starline( )

{ int a;

for(a=1; a<60; a++)

printf(“%c”, ‘*’);

printf(“\n”);

return;

}

main( )

{

statement1( );

Starline( );

getch();

return 0;

}

Page 202: Es202 Lecture Notes

Functions with no arguments but with return values

THINK OF AN EXAMPLE?

Page 203: Es202 Lecture Notes

Functions with arguments and no return values

THINK OF AN EXAMPLE!!!

Page 204: Es202 Lecture Notes

Functions with arguments and return values

THINK OF AN EXAMPLE!!!

Page 205: Es202 Lecture Notes

Return value data type of function:

A C function returns a value of type int as the default data type when no other type is specified explicitly.

Page 206: Es202 Lecture Notes

Parameter Passing

Two types:

1. Pass by reference - the variable argument is renamed, not copied. Only the address of the argument is passed to the function.

2. Pass by value - a copy of the data is passed to the subroutine, so that no matter what happens to the copy the original is unaffected.

Page 207: Es202 Lecture Notes

TRANSMISSION BY VALUE

This means that the value of the actual parameter is transmitted to the formal parameter when the function is called.

Page 208: Es202 Lecture Notes

Exampleint feetToInches(int feet)

{

int inches;

inches = feet * 12;

return inches;

}

main()

{

int f = 5; i = 0;

i= feetToInches(f);

}

i

f

inches

feet

0

5

60

5

Value is copied at the point of call

Page 209: Es202 Lecture Notes

TRANSMISSION BY VALUE

Transmission by value therefore means, that the formal parameter is evaluated at the point of call, then the value of the actual parameter is transmitted to the formal parameter.

Page 210: Es202 Lecture Notes

Example 2

void changeMe(int x){ x = x * 10;}

main(){ int x; changeMe(x); printf(“%d”, x);}

What is the output of the function?

Page 211: Es202 Lecture Notes

Solution

void changeMe(int x)

{

x = x * 10;

}

main()

{

int x=5;

changeMe(x);

printf(“%d”, x);

}

x

x

5

50

Page 212: Es202 Lecture Notes

Function Prototype

The Function prototype serves the following purposes :

1) It tells the return type of the data that the function will return.

2) It tells the number of arguments passed to the function.

3) It tells the data types of the each of the passed arguments.

4) Also it tells the order in which the arguments are passed to the function.

Page 213: Es202 Lecture Notes

Example

#include <stdio.h>

int sum (int, int); // This is a function prototype

int main (void)

{ int total;

total = sum (2, 3);

printf ("Total is %d\n", total);

return 0;

}

int sum (int a, int b)

{ return a + b; }

Page 214: Es202 Lecture Notes

Function Prototype

Question: What will happen if you did not

declare a function prototype?

Answer: Function definition should be made

before the main.

Page 215: Es202 Lecture Notes

Example

#include<stdio.h>#include<conio.h>

int add(int a, int b){ return a+b;}

main(){ int answer; answer=add(5,7);printf("The sum is: %d", answer);getch();return 0;}

Page 216: Es202 Lecture Notes

Function Prototype

You can write the definition of your function any anywhere if you declare the function prototype since the compiler knows before hand looking at the prototype that it is going to encounter the function at some point of time

Page 217: Es202 Lecture Notes

Additional ProblemsA function called Grader that takes a numeric score and returns a letter grade. Grader has one argument of type integer and returns a value of type char. Use the rule that 90 to 100 is an A, 80 to 90 is a B, 70 to 79 is a C, and less than 70 is an F.

Make a function that will compute the average of numbers from 1 to n. The prototype of this function is int average (int n);

Make a function that will return 1 if b is a factor of N, otherwise it will return 0. The function prototype is int isFactor(int N, int b) ;

Page 218: Es202 Lecture Notes

The Least Common Multiple (LCM) of two numbers is the smallest number (not zero) that is a multiple of both . For example, the least common multiple of 3 and 4 is 12. Write a function declaration for a function with two integer arguments that returns their least common multiple.

Write a function that shall accepts an array of integers of size 10. Return the sum of the 10 integers.

NOTE: Go back to the definition of array!

Page 219: Es202 Lecture Notes

ARRAY

a data structure which hold multiple variables of the same data type.

To refer to an element, specify–Array name (is a variable that contains the address of its first element)–Position number

Question: Is array uses pass by value or reference?

Page 220: Es202 Lecture Notes

ARRAY

When an array is passed as parameter, it is always the address that automatically gets transmitted.

Page 221: Es202 Lecture Notes

Sample Program

#include<stdio.h>#include<conio.h>

int add(int []);

int add(int a[]){ int x, sum=0; for(x=0; x<=9; x++) sum=sum+a[x]; return sum;}

int main(){ int num[10], y, value; for(y=0; y<=9; y++) { printf("Enter a Number%d:", y); scanf("%d",&num[y]); }value=add(num);printf("\nThe sum of all numbers is: %d",value);getch();return 0;}

Page 222: Es202 Lecture Notes

☻ IN A NUTSHELL ☻

When an expression is passed as an argument to a function, a copy of the value of the expression is made, and it is this copy that is passed to the function. This mechanism is known as

call-by-valueand is strictly adhered to in C

programming language.

Page 223: Es202 Lecture Notes

In other programming languages, however, such a function call can change the value of variable v in the calling environment. The mechanism that accomplishes this –is known as call-by-reference. To get the effect of call-by-reference in C, we must use pointers in the parameter list in the function definition, and pass addresses of variables as arguments in the function call.

Page 224: Es202 Lecture Notes

Additional Problem

1. Construct a function that will print out the contents of the array of 10 numbers.

2. Construct a function that will compute the sum of the contents of the array of 10 numbers and return its result back to the calling function

Page 225: Es202 Lecture Notes

RECURSION

What is Recursion?

The joke goes that in order to understand recursion, you must understand recursion. The humor in this seems to lie in 2 places. First, a recursive function is a function that calls it self, thus understanding recursion to understand recursion seems like a call to itself. Second, that recursion is tough to understand, and so it seems like some people get it and others don’t.

Page 226: Es202 Lecture Notes

Recursion

To understand recursion, you must understand that the basic unit of recursion is the function call. In fact, if you avoid using loops and use only recursion, you will find that your function code will generally be much shorter.

Page 227: Es202 Lecture Notes

Example

Problem

Use recursion to compute the factorial of a given number “n”.

Page 228: Es202 Lecture Notes

Solution

#include<stdio.h>#include<conio.h>

int factorial(int);

int main(){ int num, fact; printf("Enter a Number: ");scanf("%d",&num);fact=factorial(num);printf("The factorial of %d is %d",num, fact); getch();return 0;}

int factorial(int x){ if(x==1) return 1;else return factorial(x-1)*x; /* This part here is the recursion*/}

Page 229: Es202 Lecture Notes

Another solution (simpler)

int factorial( int num ); /* Function prototype */

int main(){int result, number;number = 10;...result = factorial( number );}

int factorial( int num ) /* Function definition */{...if ( num > 0 ) return( num * factorial( num - 1 ) );}

Page 230: Es202 Lecture Notes

More Examples

Another example, consider the problem of summing values of an array. What's the difference between summing an array of 100 elements versus summing an array of 50 elements?

Page 231: Es202 Lecture Notes

ITERATION OR RECURSION?

It's a matter of debate whether, for a particular function, a recursive definition is clearer than an iterative one. Usually, an iterative definition will include more local variable declarations.

Page 232: Es202 Lecture Notes

ITERATION OR RECURSION?

In other words, temporary memory allocation is made explicit in the iterative versions of the functions by declaring variables, whereas it is implicit in the recursive definitions

Page 233: Es202 Lecture Notes

ITERATION OR RECURSION?

Because of extra stack manipulation, recursive versions of functions often run slower and use more memory than their iterative counterparts. But this is not always the case, and recursion can sometimes make code easier to understand.

Page 234: Es202 Lecture Notes

ITERATION OR RECURSION?

So whether a function is defined recursively or iteratively is to some extent a matter of taste.

Page 235: Es202 Lecture Notes

ES202

THE END