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

Size: px
Start display at page:

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

Transcription

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

2 Computer Programming Previously on Bil 200 Midterm Exam - 1

3 Midterm Exam students Curve: 49,78

4 Computer Programming Arrays Arrays List of variables: [ ]

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

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

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

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

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

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

11 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] The array index starts from 0. and ends at N-1

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

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

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

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

16 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 In order to randomize the generation, use fhe following function: "srand(time(null));". The function time( ) requires including "time.h".

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

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

19 Exercise Write the following program and see that the result is NOT #include <stdio.h> void main() { float top = 0.0; int i; It will display on the screen. for(i=0;i<10000;i++) { top += ; printf("toplam = %f\n", top);

20 Why? Floating point numbers are not exactly real numbers. Floating point numbers are represented by inverse powers of 2 (binary representation). Each will not be precisely , so when we add them times, the result will be different. For a better precision, use double. But it will cost more memory.

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

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

23 Introduction to Programming Languages C Libraries C Liabraries "math.h", "stdlib.h", "string.h"

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

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

26 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 = ) 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

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

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

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

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

31 pi = yaklaşık = hata = Press any key to continue

32 time(null) Gives number of seconds since 01/01/1970 At 13:40 on 17/11/2015, its value was. zaman: #include<stdio.h> #include<time.h> void main(){ int t; t = time(null); printf("zaman: %d \n", t);

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

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

35 Computer Programming Functions Functions The modules that are written by the programmer

36 Computer Programming Functions 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

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

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

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

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

41 Introduction to Programming Languages Functions 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

42 Introduction to Programming Languages Functions 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) ;

43 Introduction to Programming Languages Functions 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.

44 Introduction to Programming Languages Functions 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.

45 Introduction to Programming Languages Functions 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.

46 Introduction to Programming Languages Functions 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 ) ;

47 Introduction to Programming Languages Functions 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.

48 Introduction to Programming Languages Functions 3. Function calls main() data memory i 12 j 25 copied copied toplam() data memory a b 45 k copied c 45

49 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 some variable. Inputs are an int and a char. One of the functions whose prototype was declared. It is fully defined here. The I/O style of this and its prototype are compatible.

50 ... 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; 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). /* As a result, this function adopts a value at the place where it is called. */

51 Introduction to Programming Languages Functions 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).

52 Introduction to Programming Languages Functions General function syntax

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

54 Introduction to Programming Languages Functions 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.

55 Introduction to Programming Languages Functions Exercise: factorial program #include <stdio.h> int factorial( int x); for (i = 0 ; i < 10 ; i++ ) { printf("%d! = %d\n", i, factorial(i)); void main() { int i;

56 Introduction to Programming Languages Functions 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 ;

57 Introduction to Programming Languages Functions 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.

58 Introduction to Programming Languages Functions 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));

59 Introduction to Programming Languages Functions - Phylosophy 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.

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

Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries 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,

More information

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

Computer Programming 6th Week Functions (Function definition, function calls), Computer Programming 6th Week Functions (Function definition, function calls), Hazırlayan Asst. Prof. Dr. Tansu Filik Computer Programming Previously on Bil-200 loops (do-while, for), Arrays, array operations,

More information

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

6-1 (Function). (Function) !*+!#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x (Function) -1.1 Math Library Function!"#! $%&!'(#) preprocessor directive #include !*+!"#!, Function Description Example sqrt(x) square root of x sqrt(900.0) is 30.0 sqrt(9.0) is 3.0 exp(x) log(x)

More information

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

Lecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch Lecture 3 CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions Review Conditions: if( ) / else switch Loops: for( ) do...while( ) while( )... 1 Examples Display the first 10

More information

C Functions. 5.2 Program Modules in C

C Functions. 5.2 Program Modules in C 1 5 C Functions 5.2 Program Modules in C 2 Functions Modules in C Programs combine user-defined functions with library functions - C standard library has a wide variety of functions Function calls Invoking

More information

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

Assoc. Prof. Dr. Tansu FİLİK Assoc. Prof. Dr. Tansu FİLİK Previously on Bil 200 Low-Level I/O getchar, putchar, getc, putc Control Structures if-else, switch-case, loops (while, dowhile, for loops) for loop (generic) A disturbingly

More information

Functions. Systems Programming Concepts

Functions. Systems Programming Concepts Functions Systems Programming Concepts Functions Simple Function Example Function Prototype and Declaration Math Library Functions Function Definition Header Files Random Number Generator Call by Value

More information

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

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4 BIL 104E Introduction to Scientific and Engineering Computing Lecture 4 Introduction Divide and Conquer Construct a program from smaller pieces or components These smaller pieces are called modules Functions

More information

ECET 264 C Programming Language with Applications

ECET 264 C Programming Language with Applications ECET 264 C Programming Language with Applications Lecture 10 C Standard Library Functions Paul I. Lin Professor of Electrical & Computer Engineering Technology http://www.etcs.ipfw.edu/~lin Lecture 10

More information

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

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Lecture 9 Functions Dr M Kasim A Jalil Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Objectives In this chapter, you will learn: To understand how to construct programs modularly

More information

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

Assoc. Prof. Dr. Tansu FİLİK Assoc. Prof. Dr. Tansu FİLİK Computer Programming Previously on Bil 200 Introduction to pointers String (character array) Static and automatic variables static and automatic variables, and scope Rem: Static

More information

C Programs: Simple Statements and Expressions

C Programs: Simple Statements and Expressions .. Cal Poly CPE 101: Fundamentals of Computer Science I Alexander Dekhtyar.. C Programs: Simple Statements and Expressions C Program Structure A C program that consists of only one function has the following

More information

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

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University C Programming Notes Dr. Karne Towson University Reference for C http://www.cplusplus.com/reference/ Main Program #include main() printf( Hello ); Comments: /* comment */ //comment 1 Data Types

More information

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

C Functions. CS 2060 Week 4. Prof. Jonathan Ventura CS 2060 Week 4 1 Modularizing Programs Modularizing programs in C Writing custom functions Header files 2 Function Call Stack The function call stack Stack frames 3 Pass-by-value Pass-by-value and pass-by-reference

More information

CSE123. Program Design and Modular Programming Functions 1-1

CSE123. Program Design and Modular Programming Functions 1-1 CSE123 Program Design and Modular Programming Functions 1-1 5.1 Introduction A function in C is a small sub-program performs a particular task, supports the concept of modular programming design techniques.

More information

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

Assoc. Prof. Dr. Tansu FİLİK Assoc. Prof. Dr. Tansu FİLİK Bil 200 Week -2 Previously on Bil 200 Programming Languages (Machine Code, Assembly code, high-level languages) Compiler (translator) Software development (components of algorithm)

More information

Chapter 5 C Functions

Chapter 5 C Functions Chapter 5 C Functions Objectives of this chapter: To construct programs from small pieces called functions. Common math functions in math.h the C Standard Library. sin( ), cos( ), tan( ), atan( ), sqrt(

More information

Introduction to C Language

Introduction to C Language Introduction to C Language Instructor: Professor I. Charles Ume ME 6405 Introduction to Mechatronics Fall 2006 Instructor: Professor Charles Ume Introduction to C Language History of C Language In 1972,

More information

Fundamentals of Programming & Procedural Programming

Fundamentals of Programming & Procedural Programming Universität Duisburg-Essen PRACTICAL TRAINING TO THE LECTURE Fundamentals of Programming & Procedural Programming Session Eight: Math Functions, Linked Lists, and Binary Trees Name: First Name: Tutor:

More information

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

Function Example. Function Definition. C Programming. Syntax. A small program(subroutine) that performs a particular task. Modular programming design What is a Function? C Programming Lecture 8-1 : Function (Basic) A small program(subroutine) that performs a particular task Input : parameter / argument Perform what? : function body Output t : return

More information

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

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from INTRODUCTION TO C++ FUNCTIONS Original slides are from http://sites.google.com/site/progntut/ Dept. of Electronic Engineering, NCHU Outline 2 Functions: Program modules in C Function Definitions Function

More information

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

Programming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming. Programming Fundamentals for Engineers - 0702113 7. Functions Muntaser Abulafi Yacoub Sabatin Omar Qaraeen 1 Modular programming Your program main() function Calls AnotherFunction1() Returns the results

More information

CS3157: Advanced Programming. Outline

CS3157: Advanced Programming. Outline CS3157: Advanced Programming Lecture #8 Feb 27 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline More c Preprocessor Bitwise operations Character handling Math/random Review for midterm Reading: k&r ch

More information

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

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR 1 Functions Functions are everywhere in C Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Introduction Function A self-contained program segment that carries

More information

Computer Programming: 8th Week Pointers

Computer Programming: 8th Week Pointers Computer Programming: 8th Week Pointers Hazırlayan Asst. Prof. Dr. Tansu Filik Computer Programming Previously on Bil-200 Recursive functions, two way communications with functions (reference) Meanings

More information

Multiple Choice Questions ( 1 mark)

Multiple Choice Questions ( 1 mark) Multiple Choice Questions ( 1 mark) Unit-1 1. is a step by step approach to solve any problem.. a) Process b) Programming Language c) Algorithm d) Compiler 2. The process of walking through a program s

More information

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

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3). cs3157: another C lecture (mon-21-feb-2005) C pre-processor (1). today: C pre-processor command-line arguments more on data types and operators: booleans in C logical and bitwise operators type conversion

More information

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

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University Lesson #3 Variables, Operators, and Expressions Variables We already know the three main types of variables in C: int, char, and double. There is also the float type which is similar to double with only

More information

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

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan. Functions Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2009 Fall Outline 5.1 Introduction 5.3 Math Library Functions 5.4 Functions 5.5

More information

Chapter 4 Functions By C.K. Liang

Chapter 4 Functions By C.K. Liang 1 Chapter 4 Functions By C.K. Liang What you should learn? 2 To construct programs modularly from small pieces called functions Math functions in C standard library Create new functions Pass information

More information

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

Assoc. Prof. Dr. Tansu FİLİK Assoc. Prof. Dr. Tansu FİLİK Previously on Bil 200 Operators Logical and arithmetic operators Control Structures if-else mechanism Low-level I/O They are fast! Might be useful for console applications.

More information

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.

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. Chapter-12 FUNCTIONS Introduction 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. Types of functions There are two types

More information

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

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction Functions Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur Programming and Data Structure 1 Function Introduction A self-contained program segment that

More information

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

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University Fundamental Data Types CSE 130: Introduction to Programming in C Stony Brook University Program Organization in C The C System C consists of several parts: The C language The preprocessor The compiler

More information

Computer Programming 3 th Week Variables, constant, and expressions

Computer Programming 3 th Week Variables, constant, and expressions 3 th Week Variables, constant, and expressions Hazırlayan Asst. Prof. Dr. Tansu Filik Previously on Bil 200 Unitary operations (applied to single variable, +.-,++,--) Type casting Operation/Operator precedence

More information

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

Functions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa Functions Autumn Semester 2009 Programming and Data Structure 1 Courtsey: University of Pittsburgh-CSD-Khalifa Introduction Function A self-contained program segment that carries out some specific, well-defined

More information

today cs3157-fall2002-sklar-lect05 1

today cs3157-fall2002-sklar-lect05 1 today homework #1 due on monday sep 23, 6am some miscellaneous topics: logical operators random numbers character handling functions FILE I/O strings arrays pointers cs3157-fall2002-sklar-lect05 1 logical

More information

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

Visual Studio. Visual Studio is an extremely complex interactive development environment capable of handling many languages and tools. Tips and Tricks Topics Visual Studio Handling Output to the Screen Handling Input from the Keyboard Simple Text Menus When to use a For Loop When to use a While Loop Reviewing a Function Visual Studio

More information

Fundamentals of Computer Programming Using C

Fundamentals of Computer Programming Using C CHARUTAR VIDYA MANDAL S SEMCOM Vallabh Vidyanagar Faculty Name: Ami D. Trivedi Class: FYBCA Subject: US01CBCA01 (Fundamentals of Computer Programming Using C) *UNIT 3 (Structured Programming, Library Functions

More information

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science Functions in C C Programming and Software Tools N.C. State Department of Computer Science Functions in C Functions are also called subroutines or procedures One part of a program calls (or invokes the

More information

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

Computer Programming: 7th Week Functions, Recursive Functions, Introduction to Pointers Computer Programming: 7th Week Functions, Recursive Functions, Introduction to Pointers Hazırlayan Asst. Prof. Dr. Tansu Filik Introduction to Programming Languages Previously on Bil-200 Functions: Function

More information

1001ICT Introduction To Programming Lecture Notes

1001ICT Introduction To Programming Lecture Notes 1001ICT Introduction To Programming Lecture Notes School of Information and Communication Technology Griffith University Semester 1, 2015 1 M Environment console M.1 Purpose This environment supports programming

More information

Programming in C. Part 1: Introduction

Programming in C. Part 1: Introduction Programming in C Part 1: Introduction Resources: 1. Stanford CS Education Library URL: http://cslibrary.stanford.edu/101/ 2. Programming in ANSI C, E Balaguruswamy, Tata McGraw-Hill PROGRAMMING IN C A

More information

Lecture 04 FUNCTIONS AND ARRAYS

Lecture 04 FUNCTIONS AND ARRAYS Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions

More information

C Functions Pearson Education, Inc. All rights reserved.

C Functions Pearson Education, Inc. All rights reserved. 1 5 C Functions 2 Form ever follows function. Louis Henri Sullivan E pluribus unum. (One composed of many.) Virgil O! call back yesterday, bid time return. William Shakespeare Call me Ishmael. Herman Melville

More information

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

Introduction to Computers II Lecture 4. Dr Ali Ziya Alkar Dr Mehmet Demirer Introduction to Computers II Lecture 4 Dr Ali Ziya Alkar Dr Mehmet Demirer 1 Contents: Utilizing the existing information Top-down design Start with the broadest statement of the problem Works down to

More information

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

Technical Questions. Q 1) What are the key features in C programming language? Technical Questions Q 1) What are the key features in C programming language? Portability Platform independent language. Modularity Possibility to break down large programs into small modules. Flexibility

More information

Introduction to Programming

Introduction to Programming Introduction to Programming session 9 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2010 These slides are created using Deitel s slides Sahrif University of Technology Outlines

More information

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

C Tutorial: Part 1. Dr. Charalampos C. Tsimenidis. Newcastle University School of Electrical and Electronic Engineering. C Tutorial: Part 1 Dr. Charalampos C. Tsimenidis Newcastle University School of Electrical and Electronic Engineering September 2013 Why C? Small (32 keywords) Stable Existing code base Fast Low-level

More information

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number

More information

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University AN OVERVIEW OF C, PART 3 CSE 130: Introduction to Programming in C Stony Brook University FANCIER OUTPUT FORMATTING Recall that you can insert a text field width value into a printf() format specifier:

More information

Standard Library Functions Outline

Standard Library Functions Outline Standard Library Functions Outline 1. Standard Library Functions Outline 2. Functions in Mathematics #1 3. Functions in Mathematics #2 4. Functions in Mathematics #3 5. Function Argument 6. Absolute Value

More information

Functions in C C Programming and Software Tools

Functions in C C Programming and Software Tools Functions in C C Programming and Software Tools N.C. State Department of Computer Science Functions in C Functions are also called subroutines or procedures One part of a program calls (or invokes the

More information

Programming and Data Structure

Programming and Data Structure Programming and Data Structure Sujoy Ghose Sudeshna Sarkar Jayanta Mukhopadhyay Dept. of Computer Science & Engineering. Indian Institute of Technology Kharagpur Spring Semester 2012 Programming and Data

More information

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions C++ PROGRAMMING SKILLS Part 3 User-Defined Functions Introduction Function Definition Void function Global Vs Local variables Random Number Generator Recursion Function Overloading Sample Code 1 Functions

More information

Function. specific, well-defined task. whenever it is called or invoked. A function to add two numbers A function to find the largest of n numbers

Function. specific, well-defined task. whenever it is called or invoked. A function to add two numbers A function to find the largest of n numbers Functions 1 Function n A program segment that carries out some specific, well-defined task n Example A function to add two numbers A function to find the largest of n numbers n A function will carry out

More information

C: How to Program. Week /Apr/23

C: How to Program. Week /Apr/23 C: How to Program Week 9 2007/Apr/23 1 Review of Chapters 1~5 Chapter 1: Basic Concepts on Computer and Programming Chapter 2: printf and scanf (Relational Operators) keywords Chapter 3: if (if else )

More information

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

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been

More information

from Appendix B: Some C Essentials

from Appendix B: Some C Essentials from Appendix B: Some C Essentials tw rev. 22.9.16 If you use or reference these slides or the associated textbook, please cite the original authors work as follows: Toulson, R. & Wilmshurst, T. (2016).

More information

Decision Making and Loops

Decision Making and Loops Decision Making and Loops Goals of this section Continue looking at decision structures - switch control structures -if-else-if control structures Introduce looping -while loop -do-while loop -simple for

More information

School of Computer Science Introduction to Algorithms and Programming Winter Midterm Examination # 1 Wednesday, February 11, 2015

School of Computer Science Introduction to Algorithms and Programming Winter Midterm Examination # 1 Wednesday, February 11, 2015 Page 1 of 8 School of Computer Science 60-141-01 Introduction to Algorithms and Programming Winter 2015 Midterm Examination # 1 Wednesday, February 11, 2015 Marking Exemplar Duration of examination: 75

More information

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

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved. Functions In general, functions are blocks of code that perform a number of pre-defined commands to accomplish something productive. You can either use the built-in library functions or you can create

More information

Procedural Programming & Fundamentals of Programming

Procedural Programming & Fundamentals of Programming & Fundamentals of Programming Exercise 4 (SS 2018) 12.06.2018 What will I learn in the 5. exercise Files Math functions Dynamic data structures (linked Lists) Exercise(s) 1 Files A file can be seen as

More information

LAB 7 FUNCTION PART 2

LAB 7 FUNCTION PART 2 LAB 7 FUNCTION PART 2 School of Computer and Communication Engineering Universiti Malaysia Perlis 1 OBJECTIVES 1. To differentiate the file scope and block scope. 2. To write recursive function. 3. To

More information

UNIT-I Input/ Output functions and other library functions

UNIT-I Input/ Output functions and other library functions Input and Output functions UNIT-I Input/ Output functions and other library functions All the input/output operations are carried out through function calls. There exists several functions that become

More information

BSM540 Basics of C Language

BSM540 Basics of C Language BSM540 Basics of C Language Chapter 9: Functions I Prof. Manar Mohaisen Department of EEC Engineering Review of the Precedent Lecture Introduce the switch and goto statements Introduce the arrays in C

More information

H192 Midterm 1 Review. Tom Zajdel

H192 Midterm 1 Review. Tom Zajdel H192 Midterm 1 Review Tom Zajdel Declaring variables Need to specify a type when declaring a variable. Can declare multiple variables in one line. int x, y, z; float a, b, c; Can also initialize in same

More information

C Programming Multiple. Choice

C Programming Multiple. Choice C Programming Multiple Choice Questions 1.) Developer of C language is. a.) Dennis Richie c.) Bill Gates b.) Ken Thompson d.) Peter Norton 2.) C language developed in. a.) 1970 c.) 1976 b.) 1972 d.) 1980

More information

ALGORITHM 2-1 Solution for Exercise 4

ALGORITHM 2-1 Solution for Exercise 4 Chapter 2 Recursion Exercises 1. a. 3 * 4 = 12 b. (2 * (2 * fun1(0) + 7) + 7) = (2 * (2 * (3 * 0) + 7) + 7) = 21 c. (2 * (2 * fun1(2) + 7) + 7) = (2 * (2 * (3 * 2) + 7) + 7) = 45 2. a. 3 b. (fun2(2, 6)

More information

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

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 5. Playing with Data Modifiers and Math Functions Getting Controls Readin from and Writint to Standart I/O BIL104E: Introduction to Scientific and Engineering Computing Lecture 5 Playing with Data Modifiers and Math Functions Getting Controls Pointers What Is a Pointer?

More information

Chapter 1 Getting Started Structured Programming 1

Chapter 1 Getting Started Structured Programming 1 Chapter 1 Getting Started 204112 Structured Programming 1 Outline Introduction to Programming Algorithm Programming Style The printf( ) Function Common Programming Errors Introduction to Modularity Top-Down

More information

C introduction: part 1

C introduction: part 1 What is C? C is a compiled language that gives the programmer maximum control and efficiency 1. 1 https://computer.howstuffworks.com/c1.htm 2 / 26 3 / 26 Outline Basic file structure Main function Compilation

More information

C Programming Language

C Programming Language C Programming Language Arrays & Pointers I Dr. Manar Mohaisen Office: F208 Email: manar.subhi@kut.ac.kr Department of EECE Review of Precedent Class Explain How to Create Simple Functions Department of

More information

More examples for Control statements

More examples for Control statements More examples for Control statements C language possesses such decision making capabilities and supports the following statements known as control or decision-making statements. 1. if statement 2. switch

More information

Procedural Programming

Procedural Programming Exercise 6 (SS 2016) 04.07.2015 What will I learn in the 6. exercise Math functions Dynamic data structures (linked Lists) Exercise(s) 1 Home exercise 4 (3 points) Write a program which is able to handle

More information

UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING

UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING APS 105 Computer Fundamentals Midterm Examination October 20, 2011 6:15 p.m. 8:00 p.m. (105 minutes) Examiners: J. Anderson, T. Fairgrieve,

More information

ESC101N: Fundamentals of Computing End-sem st semester

ESC101N: Fundamentals of Computing End-sem st semester ESC101N: Fundamentals of Computing End-sem 2010-11 1st semester Instructor: Arnab Bhattacharya 8:00-11:00am, 15th November, 2010 Instructions 1. Please write your name, roll number and section below. 2.

More information

Precedence and Associativity Table. % specifiers in ANSI C: String Control Codes:

Precedence and Associativity Table. % specifiers in ANSI C: String Control Codes: CMPE108, Homework-2 (C Fundamentals, Expressions, and Selection Structure.) Student Nr:... Name,Surname:...:... CMPE108 Group:... Signature... Please print this homework, and solve all questions on the

More information

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

CpSc 1111 Lab 6 Conditional Statements, Loops, the Math Library, and Random Numbers What s the Point? CpSc 1111 Lab 6 Conditional Statements, Loops, the Math Library, and Random Numbers What s the Point? Overview For this lab, you will use: one or more of the conditional statements explained below scanf()

More information

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

int main(void) { int a, b, c; /* declaration */ &KDSWHULQ$%& #include int main(void) { int a, b, c; /* declaration */ float x, y=3.3, z=-7.7; /* declaration with initialization */ printf("input two integers: "); /* function call */ scanf("%d%d",

More information

Using Free Functions

Using Free Functions Chapter 3 Using Free Functions 3rd Edition Computing Fundamentals with C++ Rick Mercer Franklin, Beedle & Associates Goals Evaluate some mathematical and trigonometric functions Use arguments in function

More information

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

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

More information

OBJECTIVE QUESTIONS: Choose the correct alternative:

OBJECTIVE QUESTIONS: Choose the correct alternative: OBJECTIVE QUESTIONS: Choose the correct alternative: 1. Function is data type a) Primary b) user defined c) derived d) none 2. The declaration of function is called a) function prototype b) function call

More information

Fundamentals of Programming & Procedural Programming

Fundamentals of Programming & Procedural Programming Universität Duisburg-Essen PRACTICAL TRAINING TO THE LECTURE Fundamentals of Programming & Procedural Programming Session Four: Functions: Built-in, Parameters and Arguments, Fruitful and Void Functions

More information

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1 Chapter 6 Function C++, How to Program Deitel & Deitel Spring 2016 CISC1600 Yanjun Li 1 Function A function is a collection of statements that performs a specific task - a single, well-defined task. Divide

More information

ANSI C Programming Simple Programs

ANSI C Programming Simple Programs ANSI C Programming Simple Programs /* This program computes the distance between two points */ #include #include #include main() { /* Declare and initialize variables */ double

More information

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

Integer Representation. Variables. Real Representation. Integer Overflow/Underflow Variables Integer Representation Variables are used to store a value. The value a variable holds may change over its lifetime. At any point in time a variable stores one value (except quantum computers!)

More information

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

The cin Object. cout << Enter the length and the width of the rectangle? ; cin >> length >> width; The cin Object Short for console input. It is used to read data typed at the keyboard. Must include the iostream library. When this instruction is executed, it waits for the user to type, it reads the

More information

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

C Review. SWE2004: Principles in Programming Spring 2014 Euiseong Seo C Review 1 C Program Structure #include int main ( ) { variable declarations; } statements; scanf ( %d, &var); printf (..\n ); return 0; Compilation of a program: gcc o hello hello.c -o specifies

More information

Preview from Notesale.co.uk Page 2 of 79

Preview from Notesale.co.uk Page 2 of 79 COMPUTER PROGRAMMING TUTORIAL by tutorialspoint.com Page 2 of 79 tutorialspoint.com i CHAPTER 3 Programming - Environment Though Environment Setup is not an element of any Programming Language, it is the

More information

Introduction to Functions in C. Dr. Ahmed Telba King Saud University College of Engineering Electrical Engineering Department

Introduction to Functions in C. Dr. Ahmed Telba King Saud University College of Engineering Electrical Engineering Department Introduction to Functions in C Dr. Ahmed Telba King Saud University College of Engineering Electrical Engineering Department Function definition For example Pythagoras(x,y,z) double x,y,z; { double d;

More information

Basic types and definitions. Chapter 3 of Thompson

Basic types and definitions. Chapter 3 of Thompson Basic types and definitions Chapter 3 of Thompson Booleans [named after logician George Boole] Boolean values True and False are the result of tests are two numbers equal is one smaller than the other

More information

Calling Prewritten Functions in C

Calling Prewritten Functions in C Calling Prewritten Functions in C We've already called two prewritten functions that are found in the C library stdio.h: printf, scanf. The function specifications for these two are complicated (they allow

More information

MTH 307/417/515 Final Exam Solutions

MTH 307/417/515 Final Exam Solutions MTH 307/417/515 Final Exam Solutions 1. Write the output for the following programs. Explain the reasoning behind your answer. (a) #include int main() int n; for(n = 7; n!= 0; n--) printf("n =

More information

Pointers and scanf() Steven R. Bagley

Pointers and scanf() Steven R. Bagley Pointers and scanf() Steven R. Bagley Recap Programs are a series of statements Defined in functions Can call functions to alter program flow if statement can determine whether code gets run Loops can

More information

Government Polytechnic Muzaffarpur.

Government Polytechnic Muzaffarpur. Government Polytechnic Muzaffarpur. Name of the Lab: COMPUTER PROGRAMMING LAB (MECH. ENGG. GROUP) Subject Code: 1625408 Experiment: 1 Aim: Programming exercise on executing a C program. If you are looking

More information

Structured Programming. Functions and Structured Programming. Functions. Variables

Structured Programming. Functions and Structured Programming. Functions. Variables Structured Programming Functions and Structured Programming Structured programming is a problem-solving strategy and a programming methodology. The construction of a program should embody topdown design

More information

JTSK Programming in C II C-Lab II. Lecture 3 & 4

JTSK Programming in C II C-Lab II. Lecture 3 & 4 JTSK-320112 Programming in C II C-Lab II Lecture 3 & 4 Xu (Owen) He Spring 2018 Slides modified from Dr. Kinga Lipskoch Planned Syllabus The C Preprocessor Bit Operations Pointers and Arrays (Dynamically

More information

Floating-point lab deadline moved until Wednesday Today: characters, strings, scanf Characters, strings, scanf questions clicker questions

Floating-point lab deadline moved until Wednesday Today: characters, strings, scanf Characters, strings, scanf questions clicker questions Announcements Thursday Extras: CS Commons on Thursdays @ 4:00 pm but none next week No office hours next week Monday or Tuesday Reflections: when to use if/switch statements for/while statements Floating-point

More information

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

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

More information