Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries

Similar documents
Assoc. Prof. Dr. Tansu FİLİK

Computer Programming 6th Week Functions (Function definition, function calls),

Assoc. Prof. Dr. Tansu FİLİK

Lecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch

C Functions. 5.2 Program Modules in C

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Assoc. Prof. Dr. Tansu FİLİK

Functions. Systems Programming Concepts

ECET 264 C Programming Language with Applications

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

Chapter 5 C Functions

today cs3157-fall2002-sklar-lect05 1

C Programs: Simple Statements and Expressions

CSE123. Program Design and Modular Programming Functions 1-1

Multiple Choice Questions ( 1 mark)

Introduction to C Language

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

CS3157: Advanced Programming. Outline

C Functions. CS 2060 Week 4. Prof. Jonathan Ventura

Programming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming.

Computer Programming 3 th Week Variables, constant, and expressions

Fundamentals of Computer Programming Using C

Assoc. Prof. Dr. Tansu FİLİK

A function is a named group of statements developed to solve a sub-problem and returns a value to other functions when it is called.

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

Function Example. Function Definition. C Programming. Syntax. A small program(subroutine) that performs a particular task. Modular programming design

Fundamentals of Programming & Procedural Programming

Programming in C. Part 1: Introduction

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

CpSc 1111 Lab 6 Conditional Statements, Loops, the Math Library, and Random Numbers What s the Point?

UNIT-I Input/ Output functions and other library functions

1001ICT Introduction To Programming Lecture Notes

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 5. Playing with Data Modifiers and Math Functions Getting Controls

Visual Studio. Visual Studio is an extremely complex interactive development environment capable of handling many languages and tools.

Chapter 3 - Functions

Lecture 04 FUNCTIONS AND ARRAYS

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction

Note: unless otherwise stated, the questions are with reference to the C Programming Language. You may use extra sheets if need be.

ALGORITHM 2-1 Solution for Exercise 4

LAB 7 FUNCTION PART 2

Strings and Library Functions

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Lecture 14. Daily Puzzle. Math in C. Rearrange the letters of eleven plus two to make this mathematical statement true. Eleven plus two =?

Technical Questions. Q 1) What are the key features in C programming language?

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

C Functions Pearson Education, Inc. All rights reserved.

LESSON 4. The DATA TYPE char

ECET 264 C Programming Language with Applications. C Program Control

ANSI C Programming Simple Programs

H192 Midterm 1 Review. Tom Zajdel

from Appendix B: Some C Essentials

Integer Representation. Variables. Real Representation. Integer Overflow/Underflow

Introduction to Programming

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

Computer Programming: 8th Week Pointers

C Review. SWE2004: Principles in Programming Spring 2014 Euiseong Seo

Introduction to Computers II Lecture 4. Dr Ali Ziya Alkar Dr Mehmet Demirer

2. Numbers In, Numbers Out

The cin Object. cout << "Enter the length and the width of the rectangle? "; cin >> length >> width;

Expressions. Eric McCreath

Preview from Notesale.co.uk Page 2 of 79

C Programming Language

C Program Structures

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables

Macro Programming Reference Guide. Copyright 2005 Scott Martinez

Functions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa

Computer Programming: Skills & Concepts (CP) arithmetic, if and booleans (cont)

C Tutorial: Part 1. Dr. Charalampos C. Tsimenidis. Newcastle University School of Electrical and Electronic Engineering.

Data Type Fall 2014 Jinkyu Jeong

CS-201 Introduction to Programming with Java

Chapter 1 Getting Started Structured Programming 1

Chapter 4 Functions By C.K. Liang

Procedural Programming & Fundamentals of Programming

Standard Library Functions Outline

Basic types and definitions. Chapter 3 of Thompson

Procedural Programming

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

C mini reference. 5 Binary numbers 12

C Programming Multiple. Choice

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

Matlab? Chapter 3-4 Matlab and IPT Basics. Working Environment. Matlab Demo. Array. Data Type. MATLAB Desktop:

printf( Please enter another number: ); scanf( %d, &num2);

AIR FORCE SCHOOL,BAMRAULI COMPUTER SCIENCE (083) CLASS XI Split up Syllabus (Session ) Contents

int main(void) { int a, b, c; /* declaration */

Calling Prewritten Functions in C

C: How to Program. Week /Apr/23

Computer Programming: 7th Week Functions, Recursive Functions, Introduction to Pointers

2. Numbers In, Numbers Out

EECE.2160: ECE Application Programming Spring 2018 Programming Assignment #6: Using Arrays to Count Letters in Text Due Wednesday, 4/4/18, 11:59:59 PM

CT 229 Java Syntax Continued

Copy: IF THE PROGRAM or OUTPUT is Copied, then both will have grade zero.

BSM540 Basics of C Language

BİL200 TUTORIAL-EXERCISES Objective:

Review Topics. Final Exam Review Slides

Transcription:

Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries Hazırlayan Asst. Prof. Dr. Tansu Filik

Computer Programming Previously on Bil 200 Low-Level I/O getchar, putchar, getc, putc Control Structures if-else, switch-case, loops (while, do-while, for loops)

Computer Programming Exam Examples #include <stdio.h> main(void) { int i = 0, x = 0; for (i = 1; i < 10; ++i) { if( i % 2 == 1) x += i; else x--; printf("%d-", x); printf("\nx = %d", x); Write output of the program 1-0-3-2-7-6-13-12-21 x = 21 Rewrite the equivalent of the following for loop using while loop i = 1; while (i < 10) { if( i % 2 == 1) x += i; else x--; printf("%d ", x); ++i;

Computer Programming Exam Examples #include <stdio.h> main(void) { int i, j, k, x=0, y=0; for (i = 0; i < 5; ++i) for (j = 0; j<i; ++j) { switch (i + j - 1) { case -1: case 0: y +=++x; x += y; break; case 1: case 2: case 3: x += 2; default: x += 3; printf("%d ", x); printf("\nx = %d\n", x); Write output of the program #include <stdio.h> main(void) { int i, j, k, x=0, y=0; 1-0-3-2-7-6-13-12-21 x = 21 Rewrite the program by using if-else statement instead of switch statement which will give the same output. for (i = 0; i < 5; ++i) for (j = 0; j<i; ++j) { if ((i + j - 1) <= 0 ){ y += ++x; x += y; else if ((i + j - 1) > 0 && (i + j - 1) <= 3) { x += 2; x += 3; else x += 3; printf("%d ", x); printf("\nx = %d\n", x);

Computer Programming Exam Examples

Computer Programming Control structures: Loops Example: Nested for loops Consider formula: x 2 + y 2 = z 2. Here, x, y, and z are integers. As an example, for 3,4,5 triangle, 3 2 + 4 2 = 5 2. 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.

Computer Programming Example: Nested for loops #include <stdio.h> #define N 20 void main(void) { int i,j,k, karetoplam; Control structures: Loops 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);

Computer Programming Example: Nested for loops 3 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

Computer Programming Exercises: Control structures: Loops 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.

Computer Programming Exercises: Control structures: Loops 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.

Computer Programming Exercises: Control structures: Loops 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.

Computer Programming Exercises: Control structures: Loops 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.

Computer Programming Arrays Arrays List of variables: [ ]

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

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

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

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

Computer Programming Arrays int gun[7]; gun[0] gun[1] gun[2] gun[3] gun[4] gun[5] gun[6] 2 6 6 4 12 54-10 Usage examples: gun[5] = 1; if( gun[5] == 4 ) break; gun[5] = gun[6] - 1;

Computer Programming 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] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] -45 6 0 72 1543-89 0 62-3 1 6453 78 The array index starts from 0. and ends at N-1

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

Computer Programming 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 ;...

Computer Programming 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 ;

Computer Programming 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 ("gün[%d] Şubat %d, 2004\n", i, gun[i] ) ;

Computer Programming 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".

Computer Programming 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 ]) ;

Computer Programming 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; It will display 1.000054 on the screen. for(i=0;i<10000;i++) { top += 0.0001; printf("toplam = %f\n", top);

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; If the value is at the end of the array, it takes very long time. /* target and array[] is read from file */ while( (num <=sayi) && (!bulundu) ) { if(hedef == dizi[num]) bulundu = 1; else num++;

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

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

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

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

Binary search target (33) == array[mid] (33), found true Sol Orta Sağ 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 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 found is true. So, we return mid as the returned search result.

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> int main(void) { double pi, yak, hata; asin, is the arc-sine function. 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;

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 */