assoc. prof. dr. tansu fİlİkeem.eskisehir.edu.tr/tansufilik/bİl 200/icerik/bil200_week_6.pdf ·...
TRANSCRIPT
Assoc. Prof. Dr. Tansu FİLİK
Previously on Bil 200
Computer Programming
Midterm Exam - 1
Arrays
Computer Programming
ArraysList of variables: [ ]
Arrays
Computer Programming
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
Computer Programming
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
Computer Programming
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
Computer Programming
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
Computer Programming
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
Computer Programming
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
Computer Programming
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
Computer Programming
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
Computer Programming
#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
Computer Programming
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 fhefollowing function: "srand(time(NULL));".
The function “time( )” requires including "time.h".
Arrays – Example: Solution
Computer Programming
#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
Computer Programming
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 display1.000054 on the
screen.
Why?
Floating point numbers are not exactly realnumbers.
Floating point numbers are represented byinverse powers of 2 (binary representation).
Each 0.0001 will not be precisely 0.0001, sowhen we add them 10000 times, the result willbe different.
For a better precision, use double. But it will costmore 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.
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 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*/
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 pithe 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 13:40 on 17/11/2015, its value was.
zaman: 1447760273
#include<stdio.h>
#include<time.h>
void main(){
int t;
t = time(NULL);
printf("zaman: %d \n", t);
}
time(NULL)
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 sec */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 */
}}
Functions
Computer Programming
FunctionsThe modules that are written by the programmer
Functions
Computer Programming
Function Calls
Calling a function means “returning the value of a named list of commands that do a specific task”.
We may call functions that we write ourselves.
We may call functions that already exist in the standard C library.
Ex: printf, scanf, sqrt
Functions
Computer Programming
Example
Write a program which
obtains and prints out
the square-root of an
entered number.#include <stdio.h>#include <math.h>/* Ekrandan girilen bir
sayının karekökünüyazar. */
int main(){
float x, sonuc;printf("Bir sayi giriniz"); scanf("%f", &x);
sonuc = sqrt(x);printf("Sonuc = %f", sonuc);return 0;
}
Functions
Computer Programming
Until now, we wrote our program using a single function: main().
The sytax was:
void main ( )
{
/* definitions */
/* expressions */
}
The term void indicates that this function returns NOTHING.
Functions
Computer Programming
The () parantheses indicate that main is a function. Inside these parantheses, you send parameters to the function. For this particular case, we do not send anything to the function, so the parantheses are empty.
Normally, functions require a list of parameters to be sent to them for processing and generating a result. That result may be returned to the function calling place.
Functions
Computer Programming
A function can be written is three steps:
1. Function prototype declaration
2. The function itself (declaration + commands
inside)
3. The expression that calls the function.
Functions
Introduction to Programming Languages
1. Function prototypes
Compilers trace the program from top to bottom. If you write
a program which tries to use your functions, the compiler
needs to know “how” the function is called.
The prototypes are listed at the top to show the parametric
interface of functions.
void, char,
int, float,
double
semicolon
Functions
Introduction to Programming Languages
1. Function prototypes: Parameters
Parameter list is a list of types that will enter to the
function.
float toplam(int a,int b,int c) ;
Functions
Introduction to Programming Languages
2. Function definition
In the real declaration of function, do not put ; at
the end of first line.
float toplam(int a,int b, int c)
Here, the function toplam takes three variables: a, b
and c. The return type is float.
a, b and c values are sent by the place where the function is called.
Functions
Introduction to Programming Languages
2. Function definition
Function definition consists of a declaration line similar to the prototype, followed by a list of commands bounded by curly parantheses:
float toplam( int a, int b, int c)
{
float t;
t = a + b + c ;
return t;
}
Note: The function returns a value using the return keyword. If the return type is void, you do not need to use a return line.
Functions
Introduction to Programming Languages
2. Function definition
float toplam( int a, int b, int c)
{
float t;
t = a + b + c ;
return t;
}
The variables a, b and c are valid only inside the function toplam.
The variable t is also valid only inside the function, and its
memory location is freed when the function finished.
Functions
Introduction to Programming Languages
3. Function calls
While calling a function, it must be compatible with the prototype and the return type. The sent parameters must also be compatible with the types. You may send proper variables, expressions, or values to a function. For this case:
deger = toplam( i, j, k ) ;
or
deger = toplam( 5, x, 2.7 ) ;
Functions
Introduction to Programming Languages
3. Function calls
Inside the main() function, the function toplam() is called. In that case, the parameter values are copied into the parameter list variables of the function.
Functions
Introduction to Programming Languages
3. Function calls
main() data memory
12
i
25
j
45
k
toplam() data memory
copied
copied
copied
12
a
25
b
45
c
FUNCTIONS- review#include<stdio.h>void func1(void);int func2(int n, char ch);void main(void){
int i=1,j=2;char ch=‘0’;printf(“%d %d\n”,i,j);func1();j=func2(i,ch);printf(“%d %d\n”,i,j);
}void func1(void){
printf(“selam!\n”);}.......
Prototype declarations. Before using in main or other functions, declare their names like this.Their bodies will be written later.
Calling a void-type function. Result is not assigned to anything.There is no input (void).
Function generates an int type output.Therefore, its output can be assigned to somevariable. Inputs are an int and a char.
One of the functions whose prototype wasdeclared. It is fully defined here. The I/O style of this and its prototype are compatible.
....
int func2(int x, char y)
{
int z;
printf(“Basta: x=%d, y=%c\n”,x,y);
z=x*y;
printf(“Simdi: z=%d\n”,z);
return z;
} /* As a result, this function adopts a value at the place
where it is called. */
Since function generates an int ...
...an int variable is declared inside ...
...and a value is assigned to it ...
...and variable is returned (function value produced).
Functions
Introduction to Programming Languages
Prototypes are necessary if you plan to write
functions at the end of the program. In this way,
you can safely use functions within functions.
If you write functions before main, or before other
functions which call them, you do not need to use
prototypes.
In this case, if a function (a) is used in function (b),
then (a) must be written on top of (b).
Functions
Introduction to Programming Languages
General function syntax
void face(void)
{
printf(“:-)”);
}
void next_line(void)
{
printf(“\n”);
}
void faces(int n)
{
if(i<=0)
return;
else
{
for(i=1;i<=n;i++)
face();
next_line();
}
}
void main(void)
{
faces(3);
faces(2);
faces(1);
}
:-):-):-):-):-):-)
Functions
Introduction to Programming Languages
Exercise: function factorial()
Write a function to evaluate the factorial of a
number. For parameters less than zero, the return
value will be 0. For zero and one, the return value is
1, for larger numbers, use a loop to evaluate.
In the main function, write a loop to evaluate
factorials of numbers from 0 to 10, and print on the
screen.
Do not forget to write the prototype.
Functions
Introduction to Programming Languages
Exercise: factorial program
#include <stdio.h>
int factorial( int x);
void main()
{
int i;
for (i = 0 ; i < 10 ; i++ ) {
printf("%d! = %d\n", i,
factorial(i));
}
}
Functions
Introduction to Programming Languages
Exercise: factorial program
int factorial ( int x )
{
int f = 1, k;
if ( x < 0 ) return 0;
else if ( x==0 || x==1 ) {
return 1; /* Return 1 for 0 or 1
*/
}
for ( k = 2 ; k <= x ; k++ ) {
f *= k ;
}
return f ;
}
Functions
Introduction to Programming Languages
Exercise:
Write a function which takes two parameters and
returns the factorial of the difference.
Function must start as:
int factorial_diff(int a, int b)
This function may call the function factorial()
which was previously implemented.
Do not forget to write the prototypes.
Functions
Introduction to Programming Languages
Class Exercise: Main Program
#include <.......>
/* prototype */
int factorial_diff(int a, int b);
void main()
{
int a,b;
printf("Farkın alinacagi sayilari girin: ");
scanf("%d %d", &a, &b);
printf("fark= %d\n", factorial_diff(a,b));
}
Functions - Phylosophy
Introduction to Programming Languages
For early programming languages, procedural
structure was a great improvement...
Instead of a single big and nasty program;
Intelligible and easily written blocks are preferable.
Then, which parts should be made a function? How
do we decide on the structure?
How do functions communicate with each other
and with main? There must be an interface
standard.