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

Size: px
Start display at page:

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

Transcription

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

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

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

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

5 Computer Programming Exam Examples

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

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

8 Computer Programming Example: Nested for loops Control structures: Loops

9 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 is determined, the program will not output

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

11 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 is determined, the program will not output

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

13 Computer Programming Arrays Arrays List of variables: [ ]

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

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

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

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

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

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

20 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

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

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

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

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

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

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

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

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

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

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

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

32 Array operations Array search and sorting

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

34 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

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

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

37 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

38 Binary search Lets search for 33. At first, left 0, right 26, found 0: Left Right since found= false, left<= right, we say mid= (Sol+ Sağ) / 2 : Left Mid Right

39 Binary search target (33) < array[mid] (61), right mid - 1: Left Right Mid found is false, since left <= right, mid (left + right) / 2: Left Mid Right

40 Binary search target (33) < array[mid] (47), right mid - 1: left right mid found is false and left <= right, mid (left + right) / 2: left mid right

41 Binary search target (33) > array[mid] (18), left mid + 1: mid left right found is false and left <= right, mid (left + right) / 2: left mid right

42 Binary search target (33) == array[mid] (33), found true Sol Orta Sağ found is true. So, we return mid as the returned search result.

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

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

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

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

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

48 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

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

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

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

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

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

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

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

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

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 Midterm Exam - 1 Midterm Exam - 1 126 students Curve: 49,78 Computer Programming Arrays Arrays List of variables: [ ] Computer Programming

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Note: unless otherwise stated, the questions are with reference to the C Programming Language. You may use extra sheets if need be. CS 156 : COMPUTER SYSTEM CONCEPTS TEST 1 (C PROGRAMMING PART) FEBRUARY 6, 2001 Student s Name: MAXIMUM MARK: 100 Time allowed: 45 minutes Note: unless otherwise stated, the questions are with reference

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

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

Strings and Library Functions

Strings and Library Functions Unit 4 String String is an array of character. Strings and Library Functions A string variable is a variable declared as array of character. The general format of declaring string is: char string_name

More information

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

These are reserved words of the C language. For example int, float, if, else, for, while etc. Tokens in C Keywords These are reserved words of the C language. For example int, float, if, else, for, while etc. Identifiers An Identifier is a sequence of letters and digits, but must start with a letter.

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

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

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

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

LESSON 4. The DATA TYPE char

LESSON 4. The DATA TYPE char LESSON 4 This lesson introduces some of the basic ideas involved in character processing. The lesson discusses how characters are stored and manipulated by the C language, how characters can be treated

More information

ECET 264 C Programming Language with Applications. C Program Control

ECET 264 C Programming Language with Applications. C Program Control ECET 264 C Programming Language with Applications Lecture 7 C Program Control Paul I. Lin Professor of Electrical & Computer Engineering Technology http://www.etcs.ipfw.edu/~lin Lecture 7 - Paul I. Lin

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

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

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

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

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

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

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

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

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

2. Numbers In, Numbers Out

2. Numbers In, Numbers Out COMP1917: Computing 1 2. Numbers In, Numbers Out Reading: Moffat, Chapter 2. COMP1917 15s2 2. Numbers In, Numbers Out 1 The Art of Programming Think about the problem Write down a proposed solution Break

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

Expressions. Eric McCreath

Expressions. Eric McCreath Expressions Eric McCreath 2 Expressions on integers There is the standard set of interger operators in c. We have: y = 4 + 7; // add y = 7-3; // subtract y = 3 * x; // multiply y = x / 3; // integer divide

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

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

C Program Structures

C Program Structures Review-1 Structure of C program Variable types and Naming Input and output Arithmetic operation 85-132 Introduction to C-Programming 9-1 C Program Structures #include void main (void) { } declaration

More information

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

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables 1 6 C Arrays 6.2 Arrays 2 Array Group of consecutive memory locations Same name and type To refer to an element, specify Array name + position number arrayname[ position number ] First element at position

More information

Macro Programming Reference Guide. Copyright 2005 Scott Martinez

Macro Programming Reference Guide. Copyright 2005 Scott Martinez Macro Programming Reference Guide Copyright 2005 Scott Martinez Section 1. Section 2. Section 3. Section 4. Section 5. Section 6. Section 7. What is macro programming What are Variables What are Expressions

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

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

Computer Programming: Skills & Concepts (CP) arithmetic, if and booleans (cont) CP Lect 5 slide 1 Monday 2 October 2017 Computer Programming: Skills & Concepts (CP) arithmetic, if and booleans (cont) Cristina Alexandru Monday 2 October 2017 Last Lecture Arithmetic Quadratic equation

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

Data Type Fall 2014 Jinkyu Jeong

Data Type Fall 2014 Jinkyu Jeong Data Type Fall 2014 Jinkyu Jeong (jinkyu@skku.edu) 1 Syntax Rules Recap. keywords break double if sizeof void case else int static... Identifiers not#me scanf 123th printf _id so_am_i gedd007 Constants

More information

CS-201 Introduction to Programming with Java

CS-201 Introduction to Programming with Java CS-201 Introduction to Programming with Java California State University, Los Angeles Computer Science Department Lecture V: Mathematical Functions, Characters, and Strings Introduction How would you estimate

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

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

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

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

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

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

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

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University Unit 1 Programming Language and Overview of C 1. State whether the following statements are true or false. a. Every line in a C program should end with a semicolon. b. In C language lowercase letters are

More information

C mini reference. 5 Binary numbers 12

C mini reference. 5 Binary numbers 12 C mini reference Contents 1 Input/Output: stdio.h 2 1.1 int printf ( const char * format,... );......................... 2 1.2 int scanf ( const char * format,... );.......................... 2 1.3 char

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

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

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code CS102: Standard I/O Our next topic is standard input and standard output in C. The adjective "standard" when applied to "input" or "output" could be interpreted to mean "default". Typically, standard output

More information

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

Matlab? Chapter 3-4 Matlab and IPT Basics. Working Environment. Matlab Demo. Array. Data Type. MATLAB Desktop: Matlab? Lecture Slides ME 4060 Machine Vision and Vision-based Control Chapter 3-4 Matlab and IPT Basics By Dr. Debao Zhou 1 MATric LABoratory data analysis, prototype and visualization Matrix operation

More information

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

printf( Please enter another number: ); scanf( %d, &num2); CIT 593 Intro to Computer Systems Lecture #13 (11/1/12) Now that we've looked at how an assembly language program runs on a computer, we're ready to move up a level and start working with more powerful

More information

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

AIR FORCE SCHOOL,BAMRAULI COMPUTER SCIENCE (083) CLASS XI Split up Syllabus (Session ) Contents AIR FORCE SCHOOL,BAMRAULI COMPUTER SCIENCE (083) CLASS XI Split up Syllabus (Session- 2017-18) Month July Contents UNIT 1: COMPUTER FUNDAMENTALS Evolution of computers; Basics of computer and its operation;

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

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

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

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

2. Numbers In, Numbers Out

2. Numbers In, Numbers Out REGZ9280: Global Education Short Course - Engineering 2. Numbers In, Numbers Out Reading: Moffat, Chapter 2. REGZ9280 14s2 2. Numbers In, Numbers Out 1 The Art of Programming Think about the problem Write

More information

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

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 Spring 2018 Programming Assignment #6: Using Arrays to Count Letters in Text Due Wednesday, 4/4/18, 11:59:59 PM 1. Introduction In this program, you will practice working with arrays. Your program will

More information

CT 229 Java Syntax Continued

CT 229 Java Syntax Continued CT 229 Java Syntax Continued 06/10/2006 CT229 Lab Assignments Due Date for current lab assignment : Oct 8 th Before submission make sure that the name of each.java file matches the name given in the assignment

More information

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

Copy: IF THE PROGRAM or OUTPUT is Copied, then both will have grade zero. THIS IS HOMEWORK FOR PART-1 OF C/C++ COURSE Instructor: Prof Yahia Halabi Submit: Before exam-1 period [one week from 24/02/2013] Groups: Allowed to work in groups, but at the end, everyone should submit

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

BİL200 TUTORIAL-EXERCISES Objective:

BİL200 TUTORIAL-EXERCISES Objective: Objective: The purpose of this tutorial is learning the usage of -preprocessors -header files -printf(), scanf(), gets() functions -logic operators and conditional cases A preprocessor is a program that

More information

Review Topics. Final Exam Review Slides

Review Topics. Final Exam Review Slides Review Topics Final Exam Review Slides!! Transistors and Gates! Combinational Logic! LC-3 Programming!! Original slides from Gregory Byrd, North Carolina State University Modified slides by Chris Wilcox,

More information