Computer Programming 1

165
Computer Programming Using Turbo C

description

ES201_ES202 slides.ppt

Transcript of Computer Programming 1

Computer Programming UsingTurbo C

What is computer Programming?

Computer programming is creating a sequence of instructions to enable the computer to do something.

What is a programming language?

A programming language is an artificial language that can be used to control the behavior of a machine, particularly a computer.

Programming Language Translation

Source Program -- program written in a high-level programming language.

Object Program -- the source program after it has been translated into machine language.

Translator Program -- the program that translates the source program into the object program. Can be either a compiler or an interpreter.

Compilers vs. Interpreters

Compiler -- spends some time evaluating the entire program and then translates all the programming statements of a program into a machine language program, which is then executed at once.

Interpreter -- translates interactively each programming statement into an immediately usable machine language instruction. Although an interpreter slows down the execution speed of a program somewhat, it does not require extra steps to compile and link like a compiler.

In a production environment where throughput is more critical, a compiled language is preferred.

Any high-level language can either be interpreted or compiled.

                                

                                                                      

Categories of Programming

Systems programming involves writing programs that enable a computer to carry out its basic internal functions as well as some other specialized functions. Examples of systems programs include operating systems, device drivers, and utility programs.

Applications programming refers to the process of developing programs to be used for specific applications, such as a business application (e.g., computing benefits to be paid to different employee classifications) or an academic application (e.g., determining who qualifies for which scholarship, based on specified eligibility criteria).

Stages in the Applications Programming Process

1. Problem statement: The programming process begins with a clear, written statement of the problem to be solved by the computer.

2. Algorithm development: Once the problem has been clearly stated and all the requirements have been understood, the next step is to develop the program logic necessary for accomplishing the task.

*An algorithm is defined as a logical sequence of steps that must be performed in order to accomplish a given task.

• Sample Tool:Flowchart

Stages in the Applications Programming Process

3. Program coding: When the programmer is satisfied with the efficacy of the logic developed in the preceding step, it is time to convert that logic (in either flowchart or pseudo code form) to the specific syntax of the programming language that will be used.

4. Program testing: The coded program is next checked for errors.

5. Program documentation: The programming process is complete when the program has been fully documented.

Computer Programming 1

Five steps to define a programming problem:

1.Restate the problem.

2.Analyze the problem.

3. Identify the output.

4. Identify the input.

5. Identify the process.

Common Programming Errors

1.Syntax Errors

- occurs when your code violates one or more grammar rules of C and is detected by the compiler as it attempts to translate your program.

Note: If a statement has a syntax error, it cannot be translated and your program will not be executed.

Common Programming Errors

2. Run-time Errors

- are detected errors and displayed by the compiler during the execution of the program.- occurs when the program directs the computer to perform illegal operation, such as dividing a number by zero.- an attempt to perform an invalid operation, detected during program execution.

Note: When a run-time error occurs, the computer will stop executing your program and will display a diagnostic message that indicates the line where the error was detected.

Common Programming Errors

3. Logic Errors- occur when a program follows a faulty algorithm.- do not cause a run-time error and do not display error messages, so are very difficult to detect.

Note: The only sign of a logic error may be incorrect program output.

Turbo C History

Dennis Ritchie – developed Turbo C at AT&T Bell Laboratories.

Turbo C was first developed for system programming.

C Language Elements

The C Preprocessor - a program that is executed before the source code is compiled. DIRECTIVES – how C preprocessor commands are called, and begin with a pound / hash symbol (#). No white space should appear before the #, and a semi colon is NOT required at the end.

C Language Elements

Two Common Directives:1. #include – gives program access to a

library.- causes the preprocessor to insert definitions from a standard header file into the program before compilation.- tells the preprocessor that some names used in the program are found in the standard header file.

C Language Elements

Two Common Directives:2. #define – allows you to make

text substitutions before compiling the program.- by convention, all identifiers that are to be changed by the preprocessor are written in capital letters.

C Language Elements#include <stdio.h> #define MIN 0 /* #defines */ #define MAX 10 #define TRUE 1 #define FALSE 0 int main() { /* beginning of program */ int a;int okay=FALSE;/*the compiler sees this as int okay=0;*/while(!okay) {

printf("Input an integer between %d and %d: ", MIN, MAX); scanf("%d", &a); if(a>MAX) {

printf("\nToo large.\n"); } else if(a<MIN) {printf("\nToo small.\n"); } else { printf("\nThanks.\n"); okay = TRUE; }

} return 0; }

C Language Elements

Libraries – C implementations that contain collections of useful functions and symbols that may be accessed by a program.

Note: A C system may expand the number of operation available by supplying additional libraries. Each library has a standard header file whose name ends with the symbol .h.

C Language Elements

Commenting Your CodeYou can add comments to your code by enclosing

your remarks within /* and */. However, nested comments aren't allowed.

A few properties of comments: • They can be used to inform the person viewing

the code what the code does. This is helpful when you revisit the code at a later date.

• The compiler ignores all the comments. Hence, commenting does not affect the efficiency of the program.

• You can use /* and */ to comment out sections of code when it comes to finding errors, instead of deletion.

C Language Elements

Here are examples of commented code:

/* Comments spanning several *//* lines can be commented*//* out like this!*/ /* But this is a simpler way of doing it! */// These are C++ // style comments // and should NOT // be used with C!! /* /* NESTED COMMENTS ARE ILLEGAL!! */ */

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.

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.

C Language Elements

Your First Program #include <stdio.h> int main() { clrscr();printf("Hello World!\n");return 0; getch();}

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

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.

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.

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%£!!aCAN contain or begin with an underscore _height_CANNOT be a C keyword structCANNOT contain a space im stupidCAN be of mixed cases XSquared

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.

Variables, Data Types and Constants

Syntax for Declarations:

data type variable_list;

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

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: char double int

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.

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; }

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'; }

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

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

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

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’

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

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); }

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';

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();

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

Operators

Unary Operators- changes the sign of a value or

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

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

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.

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.

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

Postfix increment is when the expression’s value is the

value of the variable before it is incremented.

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

Comparison of POSTFIX and PREFIX Increments

Before… x y

5 ?

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

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

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

Prefix Postfix After… x y x y

5 6 5 5

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);}

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

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.

Predefined Mathematical Functions

FunctionPurposeabs(x) returns the absolute value of integer x.

x=abs(-5); x=5fabs(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=6

floor(x) rounds down or returns the largest whole number that is not greater than x.

x=floor(5.2); x=5

Predefined Mathematical Functions

FunctionPurposesqrt(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.

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

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);

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();

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();

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);

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”);

I/O Functions

Output Command

putchar – writes the single character to the screen.

syntax:putchar(var_name);

Example:putchar(a);

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.

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

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

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

Control Flow

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

Syntax:if (<expression>)<statement>

ConditionStatementT

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”

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.

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.

Control Flow

Syntax:

if (condition)

statementT;

else

statementF;

Condition

StatementT

Statement

F

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.

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.

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.

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;

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

Control Flow

Nested-if Statement Syntax:

if (condition){if (condition)

statement;else

statement;}

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.

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.

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.

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

Control Flow

Example

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

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”.

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. 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.

Control Flow

Switch Statement Syntax:

switch (controlling expression){case constant: statement;

break;case constant: statement;

break;. . .

default: statement;}

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

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)

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;}

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

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(); }

Control Flow

Loops and CountersLoop – a control structure that repeats a

group of steps in a program. It defines a block of code that is repeatedly executed. Depending on the kind of loop that you are using, the block of code could be executed a set number of times or until a certain condition is met.- Repetition loops can also be altered by break or continue statements.

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

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)

Control Flow

A 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.

Control Flow

3 Types:1. do-while statement2. while statement3. for statement

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.

Control Flow

Syntax:do{

statement;} while (loop repetition condition);

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

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.

Control Flow

Syntax:while (loop repetition condition){

statement;}

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

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

}

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;}

Control Flow

Examplefor (c=1; c<=5; c++)

printf(“Hello World\n”);

Example

101

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

102

Infinite Loop

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

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

Types of Loop

The following are the different types of Loops

104

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.

105

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

106

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

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.

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.

Example

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

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

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

Additional Examples

4. Make a flowchart and 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 flowchart to input 10 names of student. Each student has 5 exam scores. Determine the average exam score of each student.

Additional Examples

6. Make a flowchart and a C program to input 10 integers. Output the biggest integer.

7. Make a flowchart to input 10 names of student. Each student has 5 exam scores. Determine the average exam score of each student. Output the highest average exam score.

Arrays

Array – a group of memory locations related by the fact that they all have the same name and the same data type.

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];

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

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 ]

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.

Arrays

Initializing an array

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

n [ i ] = 0 ;

With the declaration:int n [ 10 ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 } ;int n [ 10 ] = { 0 } ;

Arrays

Storing String in Character ArraysEx: char string1[] = “first”; or

char string1[] = { ‘f’ , ’i’ , ’r’ , ’s’ , ’t’ , ’\0’ };

orscanf(“%s”, string1);printf(“%s”, string1);

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 ]

Declaring Arrays:When declaring arrays, specify

–Name–Type of array–Number of elements

arrayType arrayNam[ numberOfElements ];

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

Declaring multiple arrays of same type

Format similar to regular variables

Example:

int b[ 100 ], x[ 27 ];

Examples Using ArraysInitializers

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

Example

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

Solution:

Solution

#include <stdio.h>

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

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(); }

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’; printf("The contents of word[] is --> %s\n",

word); getch(); }

Example

#include<conio.h> #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(); }

Problem

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

Solution:

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(); }

More on Strings

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

int 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" ); }

return 0;}

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 *

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

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;

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;}

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.

Magic Square Con’t

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

Magic Square Con’t

The next simplest is the 3x3 magic square

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.

Method for constructing a magic square of odd order

Complete steps

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.

You can use continue to skip the rest of the current loop and start from the top again while incrementing the loop variable again. The following example will never print "Hello" because of the continue.

#include<stdio.h>

int main(){ int i; while (i < 10){ i++; continue; printf("Hello\n");}return 0;}

Arrays (Other Applications)

Searching Arrays

Searching – 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.

Arrays

Sorting Arrays

Sorting 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.

Functions

Function – a subroutine that contains one or more statements and performs a single well-defined task.

2 Types:1. Pre-defined – those functions written by

for us (by some other programmers).2. User-defined – those functions that we

are going to write/implement by ourselves.

Difference between the main program and the function

Main Program

Input Output

Function

Input Output

scanf() printf() parameters return

Functions

Function Syntax and Function Definition Syntax:

return_type function_name(parameter list){

local declaration;. . .statement/s;

}Note: No function can have the same name as

the one of TC’s reserved words.

Functions

Where:return_type = any standard data type in Cparameter list – consists of variables that receive the value of the arguments used in the function call.

Arguments – a value that is passed to the function at the time that it is called.

Functions

Function Definition (With return type and parameters)

Syntax:ftype fname(parameter list){

local declarationexecutable statements

}Example:

int add(int one, int two){int sum;sum = one + two;return sum;

}

Functions

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

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

}

Functions

Functions Returning ValuesThe 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.

Functions

Function Definition (Without return type and parameters)

Syntax:void fname(void){

local declarationsexecutable statements

}Example:

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

}

Functions

Function 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);

}

Parameter Passing

Two types:1. 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.

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

C Pointers

Pointers – enable programs to simulate call by reference, and to create and manipulate dynamic data structures, i.e.. Data structures that can grow and shrink, such as linked lists, queues, stacks and trees.

Pointer – a variable that contain memory addresses as their values.- It contains an address of a variable that contains a specific value.

C Pointers

Indirection – means referencing a value through a pointer.

Declaration:data_type *variable_name;

Ex:int *ptr; /*means ptr is a pointer to an integer value*/

* - indicates that the variable being declared is a pointer.

C Pointers

Directly and Indirectly referencing a variable.

count

7count directly references a variable whose value is 7

7

ptr count

ptr indirectly references a variable whose value is 7

C Pointers

Pointer OperatorsAddress operator (&) – a unary operator

that returns the address of its operand.Example:

int y = 5;int *yptr;yptr = &y; /* assigns the address of the variable y to pointer variable yptr */

C Pointers

Graphical representation of a pointer to an integer variable in memory.

5

500002

5

yptr y

500000

500002

500004

500006

500008

500010

500012

y

C Pointers

Indirection operator (*) – also known as dereferencing operator, returns the value of the object to which its operand (i.e., a pointer) points.

Example:printf(“%d”, *yptr); /* prints the value of variable y which is 5 */

C Pointers

Pointers can be assigned to one another if both pointers are of the same type.

Example:int *ptr1, *ptr2;int x=5;ptr1=&x;ptr2=ptr1;/lets ptr2 point to the variable

pointed to by ptr1*/

5

ptr1 ptr2

x

Arrays

Array – a group of memory locations related by the fact that they all have the same name and the same data type.

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];

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.

Arrays

Initializing an array

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

n [ i ] = 0 ;

With the declaration:int n [ 10 ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 } ;int n [ 10 ] = { 0 } ;

Arrays

Storing String in Character ArraysEx: char string1[] = “first”; or

char string1[] = { ‘f’ , ’i’ , ’r’ , ’s’ , ’t’ , ’\0’ };

orscanf(“%s”, string1);printf(“%s”, string1);

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.

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.