Sei sulla pagina 1di 61

Introduction to Programming

Languages
5. Week
loops (do-while, for), Arrays, array
operations, C libraries
Hazrlayan

Asst. Prof. Dr. Tansu Filik

Introduction to Programming Languages

Control structures: Loops

for
loops

Introduction to Programming Languages

Control structures: Loops

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.

Introduction to Programming Languages

Control structures: Loops

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

Introduction to Programming Languages

Control structures: Loops

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

Introduction to Programming Languages

Control structures: Loops

for loop
for( initial statements;logical expression;updates)
{
statements;
}

After the updates, the logical expression is checked. If it is


true, the loop continues.

Introduction to Programming Languages

Control structures: Loops

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.

Introduction to Programming Languages

Control structures: Loops

for loop : Example


for(;;)
{
printf(Bir sayi girin (k iin 0):);
scanf(%d,&number);
if(number==0)
break;
}
<->
for(number=1;number!=0;)
{
printf(Bir sayi girin (k iin 0):);
scanf(%d,&number);
}
<->
for(number=1;number!=0; printf(Bir sayi girin (k iin 0):),scanf(%d,&number));

Introduction to Programming Languages

Control structures: Loops

for while
statement1 ;
while ( expression2 )
{
statements ;
statement3 ;
}
for ( statement1;expression2;statement3 )
{
statements ;
}

Introduction to Programming Languages

Control structures: Loops

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

Introduction to Programming Languages

Control structures: Loops

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

Introduction to Programming Languages

Control structures: Loops

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.

Introduction to Programming Languages

Control structures: Loops

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

}
}

Introduction to Programming Languages

Control structures: Loops

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.

Introduction to Programming Languages

Control structures: Loops

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

Introduction to Programming Languages

Control structures: Loops

Example: Nested for loops


3
4
5
6
8
8
9
12
12
12
15
16

4
3
12
8
6
15
12
5
9
16
8
12

5
5
13
10
10
17
15
13
15
20
17
20

Introduction to Programming Languages

Control structures: Loops

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.

Introduction to Programming Languages

Control structures: Loops

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.

Introduction to Programming Languages

Arrays

Arrays
List of variables: [ ]

Introduction to Programming Languages

Arrays

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.

Introduction to Programming Languages

Arrays

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.

Introduction to Programming Languages

Arrays

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.

Introduction to Programming Languages

Arrays

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.

Introduction to Programming Languages

Arrays

int gun[7];

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


2

Usage examples:

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

12

54

-10

Introduction to Programming Languages

Arrays

Example
#include <stdio.h>
void main()
{
int gun [ 7 ];
int i;
for( i = 0 ; i < 7 ; i++ )
{
gun[ i ] = 0;
}
}

Bil-200

Arrays
int c[12];
c[0]=-45;
c[1]=0;
c[2]=6;
....
c[11]=78;

c[0]

-45

c[1]

c[2]

c[3]

72

c[4]

1543

c[5]

-89

c[6]

c[7]

62

c[8]

-3

c[9]
c[10]
c[11]

The array index starts from 0.


and ends at N-1

1
6453
78

Bil-200

Arrays
x=2;
c[x] == c[5-3] == c[2] == 6;
typical mistakes:

c(4)

c[1] ... c[12]

float f=1.0;
c[f];

Introduction to Programming Languages

Arrays

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

Introduction to Programming Languages

Arrays

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

Introduction to Programming Languages

Arrays - Example
#include <stdio.h>
void main()
{
int gun[7] = { 2,3,4,5,6,7,8 };
int i;
for (i = 0 ; i < 7 ; i++ ) {
printf ("gn[%d] ubat %d, 2004\n", i, gun[i] ) ;

}
}

Introduction to Programming Languages

Arrays - Example

Write a program which generates random numbers


as many as required by the user.
The random number generation function exists in a
standard library called "stdlib.h". The function
name is rand(). It generates numbers between 0
and 32767.
In order to randomize the generation, use fhe
following function: "srand(time(NULL));".
The function time( ) requires including "time.h".

Introduction to Programming Languages

Arrays Example: Solution


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

Introduction to Programming Languages

Arrays Exercise

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 values
a_size array size
target the searched value
num 1
found false
While (num <= a_size) VE (found = false)
{
if target equals array[num]
found true
else
num num + 1
}

Sequential search
#include <stdio.h>
#define UZUNLUK
10
void 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 search
Lets search for 33. At first, left 0, right 26, found 0:
Left

Right

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

10 11

12

13

14 15

16

17

18

19

20 21

22

23 24 25

26

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

Left

Mid

Right

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

10 11

12

13

14 15

16

17

18

19

20 21

22

23 24 25 26

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

Right Mid

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

10 11

12

13

14 15

16

17

18

19

20 21

22

23 24 25 26

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


Left

Mid

Right

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

10 11

12

13

14 15

16

17

18

19

20 21

22

23 24 25 26

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

right

mid

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

10 11

12

13

14 15

16

17

18

19

20 21

22

23 24 25

26

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


left

mid

right

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

10 11

12

13

14 15

16

17

18

19

20 21

22

23 24 25

26

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

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

10 11

12

13

14 15

16

17

18

19

20 21

22

23 24 25

26

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


mid
left

right

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

10 11

12

13

14 15

16

17

18

19

20 21

22

23 24 25

26

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

Sa

Sol

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

10 11

12

13

14 15

16

17

18

19

20 21

22

23 24 25

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

26

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.

Introduction to Programming Languages

C Libraries

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

Introduction to Programming Languages

C Libraries

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.

Introduction to Programming Languages

C Libraries

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(), ....

Introduction to Programming Languages

C Libraries

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

Introduction to Programming Languages

C Libraries

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 number


for(i=0; i < 100; ++i) /* 100 random numbers*/
printf("%d ", rand());

srand(value) : seed for the randomizer


srand(100); /* starting point of random
sequence*/

Introduction to Programming Languages

C Libraries

Function Libraries : time.h


time(NULL): Numbe of seconds passed since 01/01/1970.
int secs;
secs = time(NULL);

Introduction to Programming Languages

C Libraries

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>

asin, is the arc-sine


function.

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("yaklak = %.15f\n", yak);
printf("hata = %.5f", hata * 100);
return 0;

*/

pi
yaklak

= 3.141592653589793
= 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
*/
}
}

Potrebbero piacerti anche