bil200 - part05

Post on 11-Jul-2016

219 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

DESCRIPTION

computer programming

TRANSCRIPT

Hazırlayan

Introduction to Programming

Languages

5. Week

loops (do-while, for), Arrays, array

operations, C libraries

Asst. Prof. Dr. Tansu Filik

Control structures: Loops

Introduction to Programming Languages

for loops

Control structures: Loops

Introduction to Programming Languages

for loop (generic)

• A disturbingly general loop structure.

• “statement” and “expression” can be “anything”.

• The whole program, no matter how ridiculous, can be written inside a single for loop.

Control structures: Loops

Introduction to Programming Languages

for loop

for( initial statements;logical expression;updates){

statements;}

• initial statements can be used as the first commands and assignments before running the loop. These statements work only for once. You can use several statements separated by “,”.

Control structures: Loops

Introduction to Programming Languages

for loop

for( initial statements;logical expression;updates){

statements;}

• updates get executed “after” the statements in the block are executed. There may be several updates separated by “,”.

Control structures: Loops

Introduction to Programming Languages

for loop

for( initial statements;logical expression;updates){

statements;}

• After the updates, the logical expression is checked. If it is true, the loop continues.

Control structures: Loops

Introduction to Programming Languages

for loop : Notes• for is an extremely flexible structure. The statement 1-3 parts may be

completely empty, leaving everything inside the body. Yet, do not forget to use “;”.

• Skipping the first and third statements actually turn the for loop into a while loop.

• Without the second statement (in the middle), you cannot determine when to terminate the loop. In this case, you must use break somewhere inside the body to check for a termination situation.

• The first and third statements can contain multiple commands. Using such a style, you can write “single line” for loops, even without a body part.

Control structures: Loops

Introduction to Programming Languages

for loop : Examplefor(;;)

{

printf(“Bir sayi girin (çıkış için 0):”);

scanf(“%d”,&number);

if(number==0)

break;

}

< - >

for(number=1;number!=0;){

printf(“Bir sayi girin (çıkış için 0):”);scanf(“%d”,&number);

}< - >for(number=1;number!=0; printf(“Bir sayi girin (çıkış için 0):”),scanf(“%d”,&number));

Control structures: Loops

Introduction to Programming Languages

for whilestatement1 ;

while ( expression2 )

{

statements ;

statement3 ;

}

for ( statement1;expression2;statement3 ){

statements ; }

Control structures: Loops

Introduction to Programming Languages

for loops : Example#include <stdio.h>

void main ( )

{

int k, n ;

for( k = 1, n = 12 ; k<9 && n>6 ; k++, n--)

{

printf ("k=%d, n=%d\n" , k , n ) ;

}

}

Control structures: Loops

Introduction to Programming Languages

Exercises:What is the value of x when the following statement is complete?

for (x = 0 ; x < 100 ; x++) ;

What is the value of ctr when the following statement is complete?

for (ctr = 2 ; ctr < 10 ; ctr += 3) ;

How many X s does the following print?

for (x = 0; x < 10; x++)

for (y = 5; y > 0; y--)

printf("X");

Control structures: Loops

Introduction to Programming Languages

Loop termination

• The keyword “break” can be used for terminating the loop. If the loop is nested, it terminates the current block.

• The keyword “continue” is used for skipping until the end of the loop block, but the block does not terminate.

• Depending on the algorithm, you may use combinations of these keywords.

Control structures: Loops

Introduction to Programming Languages

Loop termination: break: exit loop

• In the following program, break causes the loop to finish when value of x becomes 5.

void main(){

int x = 0;

for( ; ; ) { /* infinite loop */

if(x == 5) break;printf("X = %d\n", x);x++;

}}

Control structures: Loops

Introduction to Programming Languages

Example: Nested for loops

• Consider formula: x2 + y2 = z2. Here, x, y, and z are integers.

• As an example, for 3,4,5 triangle,

• 32 + 42 = 52.

• We wish to obtain others.

• Brute force method: We may check all integer x-y couples and see if an integer z can be obtained.

Control structures: Loops

Introduction to Programming Languages

Example: Nested for loops#include <stdio.h>

#define N 20

void main(void)

{

int i,j,k, kareToplam;

for (i=1; i <= N; i++) {

for (j=1; j <= N; j++) {

kareToplam = i * i + j * j; /* x2 + y2 */

/* is there a suitable z for the x and y? */

for(k = 1 ; k <= N; k++ ) {

if (kareToplam == k * k) {

printf("%5d %5d %5d\n", i, j, k);

}

}

}

}

}

Control structures: Loops

Introduction to Programming Languages

Example: Nested for loops3 4 5

4 3 5

5 12 13

6 8 10

8 6 10

8 15 17

9 12 15

12 5 13

12 9 15

12 16 20

15 8 17

16 12 20

Control structures: Loops

Introduction to Programming Languages

Exercises:

• Can you write the previous program using only two nested loops?

• Think of a way to eliminate repetitions in the loop. In this way, once 3 4 5 is determined, the program will not output 4 3 5.

Control structures: Loops

Introduction to Programming Languages

Exercises:

• Write a program in which you can enter a string into a string variable using for loop and getchar. Whenever an enter is pressed, the new string must be available for printing with printf(“%s”,..).

• Find a simple program that converts lowercase letters to uppercase ones inside a string. Do not use long lists of if-else or switch-case. Do not use ready C functions either. You do not need to know ASCII codes of letter, either. Be smart.

Arrays

Introduction to Programming Languages

ArraysList of variables: [ ]

Arrays

Introduction to Programming Languages

Arrays

• It is the declaration of a list of same type of variables under a single name.

• An example can be the days of week. This is a 1-D array. The first element is Monday, the last is Sunday.

Arrays

Introduction to Programming Languages

Arrays

• Another example is the days of a month. This can be considered as a 1-D array, or a 2-D array whose horizontal elements are days of weeks, and vertical elements are the weeks.

• Days of a year, therefore, can be considered as a 3-D array. First dimension is days of week, second dimension is weeks of month, third dimension is months of year.

Arrays

Introduction to Programming Languages

Array declarations• A 1-D array is declared by a variable name and number of

elements inside a square bracket.• Example:

int gun [ 7 ];

gun corresponds to the array name, whose elements are of int type. There are seven elements.

• Similarly, a 2-D array is declared by two square brackets:int ay[ 4 ][ 7 ];

There are 4 rows and 7 columns of ay.

Arrays

Introduction to Programming Languages

Array usage

• Each element of an array is reached by its index written in square parantheses.

• In C, the first element is with index 0 (zero). For example, the gun array has first 0th, and last 6th element.

• The numbers inside the square parantheses are called index numbers.

Arrays

Introduction to Programming Languages

gun[0] gun[1] gun[2] gun[3] gun[4] gun[5] gun[6]

2 6 6 4 12 54 -10

int gun[7];

gun[5] = 1;if( gun[5] == 4 ) break;gun[5] = gun[6] - 1;

Usage examples:

Arrays

Introduction to Programming Languages

Example#include <stdio.h>

void main(){

int gun [ 7 ];int i;

for( i = 0 ; i < 7 ; i++ ) {

gun[ i ] = 0;}

}

Arrays

int c[12];

c[0]=-45;

c[1]=0;

c[2]=6;

....

c[11]=78;

c[6]

-45

6

0

72

1543

-89

0

62

-3

1

6453

78

c[0]

c[1]

c[2]

c[3]

c[11]

c[10]

c[9]

c[8]

c[7]

c[5]

c[4]

The array index starts from 0.

and ends at N-1

Bil-200

x=2;

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

typical mistakes:

c(4)

c[1] ... c[12]

float f=1.0;

c[f];

Arrays

Bil-200

Arrays

Introduction to Programming Languages

Initializations of arrays

We know how to initialize single variables while declaration. The situation is similar for arrays. Just use a list o values inside a block separated by “,”s.#include <stdio.h>

void main()

{

int gun[7] = { 0,2,4,6,8,10,11 };

..........

}

Arrays

Introduction to Programming Languages

Initializations of arrays

• If the array size is too big, declarative initialization is difficult. In that case, make initial assignments inside a program using loops. If we still want to make initializations, we may initialize the first few, and the rest will be zero. As an example:

int sayilar [ 10 ] = { 2 };

double dizi [ 250 ] = { 0 };

Arrays - Example

Introduction to Programming Languages

#include <stdio.h>

void main()

{

int gun[7] = { 2,3,4,5,6,7,8 };

int i;

for (i = 0 ; i < 7 ; i++ ) {

printf ("gün[%d] Şubat %d, 2004\n", i, gun[i] ) ;

}

}

Arrays - Example

Introduction to Programming Languages

• Write a program which generates random numbersas many as required by the user.

• The random number generation function exists in a standard library called "stdlib.h". The functionname is rand(). It generates numbers between 0 and 32767.

• In order to randomize the generation, use fhefollowing function: "srand(time(NULL));".

• The function “time( )” requires including "time.h".

Arrays – Example: Solution

Introduction to Programming Languages

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

#define UZUNLUK 10

void main ( )

{

int i, sayilar [UZUNLUK] ;

srand(time(NULL));

for (i = 0 ; i < UZUNLUK ; i++ ) {

sayilar[ i ] = rand ( ) ;

printf ( "sayi [ %d ] = %d\n", i, sayilar[ i ]) ;

}

}

Arrays – Exercise

Introduction to Programming Languages

• How do we generate 100 random values using the previous program structure?

• Extend the program so that it finds and writes the maximum and minimum values inside the random array. Furthermore, the program must find the average, too.

Exercise Write the following program and see that

the result is NOT 1.00000

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

float top = 0.0;int i;

for(i=0;i<10000;i++) {top += 0.0001;

}printf("toplam = %f\n", top);

}

It will display

1.000054 on the

screen.

Why?

Floating point numbers are not exactly real numbers.

Floating point numbers are represented by inverse powers of 2 (binary representation).

Each 0.0001 will not be precisely 0.0001, so when we add them 10000 times, the result will be different.

For a better precision, use double. But it will cost more memory.

Rounding errors In floating points, never use equality comparisons.

for (x = 0.0; x != 10.0; x += 0.1) {

}

Use “near” comparisons for floating points.

In some computers, the following code will result in different number of loops!

for (x = 0; x < 10.0; x += 0.1)

{

}

For loops, prefer integers.

int and char

int (32 bit) and char (8 bit) may also be

casted to each other.

int char_kod;

for (char_kod = (int) 'A'; char_kod <= (int) 'Z'; char_kod++) {

printf("%c", (char) char_kod);

}

This program prints out ABCDEFGHIJKLMNOPQRSTUVWXYZ

on the screen.

Array operations

Array search and sorting

Array operations

Array operations are very frequently used in various

programs.

In a sorted array, search can be done by simply

checking each and every element. However, there are

faster ways to do it.

A common fast method is called binary search.

Sequential search

array a list of valuesa_size array sizetarget the searched valuenum 1 found falseWhile (num <= a_size) VE (found = false){if target equals array[num]

found trueelse

num num + 1}

Sequential search #include <stdio.h>#define UZUNLUK 10void main(){

int dizi[UZUNLUK], bulundu = 0;int sayi=UZUNLUK, hedef, num = 1;

/* target and array[] is read from file */while( (num <=sayi) && (!bulundu) ) {if(hedef == dizi[num])

bulundu = 1;else

num++;}

}

If the value is at the end

of the array, it takes very

long time.

Binary search

Remember the random number generating and guessing program.

The smart guess strategy is to begin with 50. If smaller, the next is 25, otherwise, the next guess is 75i etc.

This is a best way to converge to the guessed number.

The binary search resembles this one. At each search step, it goes to the middle of the two possible boundaries.

Binary search

left 1

right LENGTH

found 0 (false)

while not found and left <= right

{

mid center of left and right

If target equals array[mid] then found 1 (true)

else if target < array[mid] then right mid – 1

else if target > array[mid] then left mid + 1

}

Binary searchLets search for 33. At first, left 0, right 26, found 0:

since found= false, left<= right, we say mid= (Sol+ Sağ) / 2 :

12 15 18 25 33 46 47 49 50 53 54 57 59 61 63 66 74 78 81 83 8868 71 90 94 97 99

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

12 15 18 25 33 46 47 49 50 53 54 57 59 61 63 66 74 78 81 83 8868 71 90 94 97 99

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

MidLeft Right

RightLeft

0 26

Binary search

target (33) < array[mid] (61), right mid - 1:

found is false, since left <= right, mid (left + right) / 2:

12 15 18 25 33 46 47 49 50 53 54 57 59 61 63 66 74 78 81 83 8868 71 90 94 97 99

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

12 15 18 25 33 46 47 49 50 53 54 57 59 61 63 66 74 78 81 83 8868 71 90 94 97 99

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

MidLeft Right

RightLeft Mid

0 26

0 26

Binary search

target (33) < array[mid] (47), right mid - 1:

found is false and left <= right, mid (left + right) / 2:

12 15 18 25 33 46 47 49 50 53 54 57 59 61 63 66 74 78 81 83 8868 71 90 94 97 99

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

12 15 18 25 33 46 47 49 50 53 54 57 59 61 63 66 74 78 81 83 8868 71 90 94 97 99

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

midleft right

rightleft mid

Binary search

target (33) > array[mid] (18), left mid + 1:

found is false and left <= right, mid (left + right) / 2:

12 15 18 25 33 46 47 49 50 53 54 57 59 61 63 66 74 78 81 83 8868 71 90 94 97 99

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

12 15 18 25 33 46 47 49 50 53 54 57 59 61 63 66 74 78 81 83 8868 71 90 94 97 99

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

midleft right

rightleftmid

Binary search

target (33) == array[mid] (33), found true

found is true. So, we return mid as the returned search result.

12 15 18 25 33 46 47 49 50 53 54 57 59 61 63 66 74 78 81 83 8868 71 90 94 97 99

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

OrtaSol Sağ

Exercise: Binary search

Create a file of 10 ascending ordered number in Notepad.

In your program, read these numbers to an array.

As the user to enter one of these 10 numbers as the target.

Implement the binary search to find the location of the target in the array (and in the file). Write the result on the screen.

Think of a way to overcome the “not exist” problem.

Exercise

Write a program in which you somehow enter

two very large (up to 30 digits) numbers and

multiply them (resulting a number with up to

60 digits. Notice that:

– There are no built in numeric types that can hold

such big integer numbers (with full precision).

Therefore you have to:

– Enter the digits into an array (use getche) and

multiply them using the algorithm they teach for

high school arithmetic.

C Libraries

Introduction to Programming Languages

C Liabraries"math.h", "stdlib.h", "string.h"

C Libraries

Introduction to Programming Languages

• The main C language only consists of expressions and grammar rules. C, itself, has NO built in function!

• Most C compilers come with the standard libraries containing several useful functions.

• In order to be able to use these functions, you must use #include directive to include the associated library containing the useful function.

C Libraries

Introduction to Programming Languages

Function Libraries• <stdio.h> - printf(), fprintf(), scanf(),

fscanf(), fopen(), putchar(), getchar(), ....

• <math.h> - pow(), sqrt(), fabs()...

• <ctype.h> - toupper(), tolower(),

isalpha(), isdigit(), ....

• <stdlib.h> - rand(), srand(), exit(), ....

C Libraries

Introduction to Programming Languages

Function Libraries : math.h• Many mathematical function (prototypes) exist here.

– fabs (x) : absolute value of float x

– sqrt (x) : square root of x

– exp (x) : e to the power x (e = 2.71828)

– log (x) : ln x

– log10 (x) : base-10 logarithm

– pow(x, y) : x to the power y

– sin (x) : sine (radians)

– cos (x) : cosine (radians)

– tan (x) : tangent

– fmod (a, b) : remainder of a/b

– ceil (x) : least integer >= x

– floor (x) : greatest integer <= x

C Libraries

Introduction to Programming Languages

Function Libraries : stdlib.h• exit(val) : used for terminating program.

if (fp == NULL)

exit(1); /* if file cannot open,

quit*/

• rand(void) : generates a random numberfor(i=0; i < 100; ++i) /* 100 random numbers*/

printf("%d ", rand());

• srand(value) : seed for the randomizersrand(100); /* starting point of random

sequence*/

C Libraries

Introduction to Programming Languages

Function Libraries : time.h• time(NULL): Numbe of seconds passed since 01/01/1970.

int secs;

secs = time(NULL);

C Libraries

Introduction to Programming Languages

Example: Approximate pi value• Pi is a very commonly used constant in mathematical

expressions.

• This number has infinite decimal points. Special applications require as many of these decimals as possible. Simple applications may be OK with 22/7.

• In the following example, we will see how near to pi the value 22/7 is.

• In C, asin(1) is approximately equal to pi.

Approximate value of pi

#include <stdio.h>#include <math.h>

int main(void) {

double pi, yak, hata;

pi = 2 * asin(1); /* realistic pi value*/yak = (double) 22 / 7; /* approximate pi */hata = fabs(yak – pi) / pi; /* find error */

printf("pi = %.15f\n", pi); /* write result */printf("yaklaşık = %.15f\n", yak);printf("hata = %.5f", hata * 100);

return 0;}

asin, is the arc-sine

function.

pi = 3.141592653589793

yaklaşık = 3.142857142857143

hata = 0.04025

Press any key to continue

time(NULL)

Gives number of seconds since 01/01/1970

At 15:00 on 01/24/2004, its value was.

Before using you should write:

#include <time.h>

Usage:

int t;

t = time(NULL);

Since each time instant is different, it is a

good randomization seed.

Clock: tik-tak#include <stdio.h>#include <time.h>

void main(void) {

int i, t;

for(i=0; i <= 10; ++i) { /* just for 10 sac */t = time(NULL) + 1; /* t next sec */

while (time(NULL) < t); /* wait */printf("tik\n"); /* write tik */

t = time(NULL) + 1; /* wait 1 sac */while(time(NULL) < t); /* wait */printf("tak\n"); /* write tak */

}}

top related