C Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Similar documents
Arrays and Applications

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

Programming for Electrical and Computer Engineers. Loops

UNIVERSITY OF WINDSOR Fall 2007 QUIZ # 2 Solution. Examiner : Ritu Chaturvedi Dated :November 27th, Student Name: Student Number:

Lecture 6 Sorting and Searching

Flow Control. CSC215 Lecture

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Indian Institute of Technology Kharagpur Programming and Data Structures (CS10001) Autumn : Mid-Semester Examination

공학프로그래밍언어 (PROGRAMMING LANGUAGE FOR ENGINEERS) -CONTROL FLOW : LOOP- SPRING 2015, SEON-JU AHN, CNU EE

Chapter 6. Loops. Iteration Statements. C s iteration statements are used to set up loops.

Computer Science & Engineering 150A Problem Solving Using Computers

Principles of Programming. Chapter 6: Arrays

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

Introduction to Computer Science Midterm 3 Fall, Points

Statements. Control Flow Statements. Relational Operators. Logical Expressions. Relational Operators. Relational Operators 1/30/14

DECISION MAKING STATEMENTS

n Group of statements that are executed repeatedly while some condition remains true

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

Introduction to Computing Lecture 07: Repetition and Loop Statements (Part II)

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

Chapter 4: Expressions. Chapter 4. Expressions. Copyright 2008 W. W. Norton & Company. All rights reserved.

COP 3223 Introduction to Programming with C - Study Union - Spring 2018

16.216: ECE Application Programming Fall 2011

Flow of Control. Selection. if statement. True and False in C False is represented by any zero value. switch

Programming for Engineers Iteration

EECE.2160: ECE Application Programming Spring 2018

Sample Examination. Family Name:... Other Names:... Signature:... Student Number:...

Functions. Chapter 5

CSE101-Lec#18. Multidimensional Arrays Application of arrays. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming

Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011

Module 6: Array in C

Lecture 6. Statements

COMP 208 Computers in Engineering

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

ECE15: Introduction to Computer Programming Using the C Language. Lecture Unit 4: Flow of Control

Programming & Data Structure Laboratory. Arrays, pointers and recursion Day 5, August 5, 2014

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

ESC101N: Fundamentals of Computing End-sem st semester

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

Decision Making -Branching. Class Incharge: S. Sasirekha

Dept. of CSE, IIT KGP

Chapter 4. Flow of Control

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

Module 4: Decision-making and forming loops

Programming & Data Structure Laboratory. Day 2, July 24, 2014

CS Introduction to Programming Midterm Exam #2 - Prof. Reed Fall 2015

More examples for Control statements

Programming for Electrical and Computer Engineers. Pointers and Arrays

Introduction. C provides two styles of flow control:

Pointers. Pointer Variables. Chapter 11. Pointer Variables. Pointer Variables. Pointer Variables. Declaring Pointer Variables

Functions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

Pace University. Fundamental Concepts of CS121 1

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

only in the space provided. Do the rough work in the space provided for it. The question paper has total 12 pages.

CSCI 2132 Software Development. Lecture 19: Generating Permutations

CSE 130 Introduction to Programming in C Control Flow Revisited

Government Polytechnic Muzaffarpur.

Structured programming

Problem Solving and 'C' Programming

C: How to Program. Week /Mar/05

CSE101-lec#19. Array searching and sorting techniques. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming

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

One Dimension Arrays 1

Control Flow, Functions and Basic Linkage

Lecture 3. More About C

Lecture 2. Examples of Software. Programming and Data Structure. Programming Languages. Operating Systems. Sudeshna Sarkar

CMPE-013/L. Introduction to C Programming. Unit testing

Solutions to Chapter 8

Arrays and Strings. Arash Rafiey. September 12, 2017

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

Engineering program development 6. Edited by Péter Vass

C Programming Lecture V

Day05 A. Young W. Lim Sat. Young W. Lim Day05 A Sat 1 / 14

Storage class and Scope:

Unit 1 - Arrays. 1 What is an array? Explain with Example. What are the advantages of using an array?

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

Slide Set 1. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

The C language. Introductory course #1

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

Comments. Comments: /* This is a comment */

PROGRAMMING IN C LAB MANUAL FOR DIPLOMA IN ECE/EEE

Fundamental of Programming (C)

Chapter 7 Functions. Now consider a more advanced example:

INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Stamp / Signature of the Invigilator

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) Introduction to arrays

Computer Programming Lecture 14 Arrays (Part 2)

UIC. C Programming Primer. Bharathidasan University

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University

FORM 2 (Please put your name and form # on the scantron!!!!)

Make sure the version number is marked on your scantron sheet. This is Version 1

Structured programming. Exercises 3

Chapter 12: Pointers and Arrays. Chapter 12. Pointers and Arrays. Copyright 2008 W. W. Norton & Company. All rights reserved.

Sorting & Searching. Hours: 10. Marks: 16

UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING

Week 2 / Lecture 2 15 March 2017 NWEN 241 Control constructs, Functions. Alvin Valera

Programming Language A

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 7

C/Java Syntax. January 13, Slides by Mark Hancock (adapted from notes by Craig Schock)

C/Java Syntax. Lecture 02 Summary. Keywords Variable Declarations Data Types Operators Statements. Functions. if, switch, while, do-while, for

Functions. (transfer of parameters, returned values, recursion, function pointers).

Transcription:

C Language Part 2 (Minor modifications by the instructor) 1

Scope Rules A variable declared inside a function is a local variable Each local variable in a function comes into existence when the function is called, and it disappears when the function is exited Temporary storage for the lifetime of the function or block Its memory is allocated in the function s stack frame Such a variable is called an automatic variable Default and implicit int foo(int n) int i; 2

Scope Rules (contd.) Function parameters (e.g., variable n in foo) are also automatic variables If we put static in the declaration of a local variable, it remains in existence throughout the program Variable i in the example below is called a static local variable int foo(int n) static int i; 3

Scope Rules (contd.) A variable declared outside any function is an external variable Permanent storage for the lifetime of the program Implicit The scope of a variable or a function is the part of the program within which the variable or the function can be used The scope of a local variable is the function in which the variable is declared The scope of an external variable or a function is from the point of its declaration to the end of the file An external variable can be accessed by all functions that follow its declaration 4

Scope Rules (contd.) Because of the scope rule, a function should be defined before it is used (called) However, C allows a function to be declared before it is #include <stdio.h> defined Forward declaration int foo(int n); int main(void) int x; foo(x); int foo(int n) #include <stdio.h> int foo(int n) int main(void) int x; foo(x); 5

Scope Rules (contd.) When we have a newly declared variable in the scope of another variable x with the same name, new x hides old x in the scope of new x #include <stdio.h> int i; /* external variable */ int foo(int n); /* forward declaration */ int main(void) int x; x = i; /* i refers to the external variable i */ int foo(int n) /* function definition */ int i; i = n; 6

Static Scope and Block Structure A block is a grouping of declarations and statements Enclosed with and A declaration D belongs to a block B if B is the most closely nested block containing D D is located within B, but not within any block that is nested within B Static-scope rule If declaration D of name x belongs to block B, then the scope of D is all of B, except for any blocks B nested to any depth within B, in which x is re-declared A name x is re-declared in B if some other declaration D of the same name x belongs to B 7

Blocks in C main() int a = 1; int b = 1; int b = 2; int a = 3; printf( %d%d\n, a, b); int b = 4; printf( %d%d\n, a, b); printf( %d%d\n, a, b); printf( %d%d\n, a, b); 8

Sequential Flow of Control Unless otherwise stated, statements in a program are executed one after another in the order they placed in the program 9

If Statement The if statement has the following form: if ( expression ) statement1 else statement2 The else part is optional If expression is evaluated to true, then statement1 is executed If it is false, statement2 is executed If it is false and there is no else part, the if statement does nothing 10

If Statement (contd.) The following if statement sets abs to be the absolute value of x if (x > 0) abs = x; else abs = -x; The following example sets min to be the minimum of i and j min = i; if (j < min) min = j; 11

If Statement (contd.) statement1 or statement2 should be a single statement Compound statement A series of declarations and statements surrounded by braces declarations statements A compound statement itself is a (single) statement if (x < 0) temp = x; x = y; y = temp; 12

Cascaded if A cascaded if statement can be used to write a multi-way decision What does the program below do? #include <stdio.h> int main(void) char op; int a = 20, b = 4; printf("select operator (+, -, *, /) : "); scanf("%c", &op); if (op == '+') printf("20 %c 4 = %d\n", op, a+b); else if (op == '-') printf("20 %c 4 = %d\n", op, a-b); else if (op == '*') printf("20 %c 4 = %d\n", op, a*b); else if (op == '/') printf("20 %c 4 = %d\n", op, a/b); else printf("wrong operator!\n"); return 0; 13

Switch Statement The switch statement also describes a multi-way decision that tests whether an expression matches one of several values The default case is optional If the default case does not exist and none of the cases match, then no action will take place switch(op) case '+': printf("20 %c 4 = %d\n", op, a+b); break; case '-': printf("20 %c 4 = %d\n", op, a-b); break; case '*': printf("20 %c 4 = %d\n", op, a*b); break; case '/': printf("20 %c 4 = %d\n", op, a/b); break; default: printf("wrong operator!\n"); break; 14

Switch Statement (contd.) The break statement causes an immediate exit from the switch statement If break is absent in a case, execution falls through to the next case switch(op) case '+': printf("20 %c 4 = %d\n", op, a+b); break; case '-': printf("20 %c 4 = %d\n", op, a-b); break; case '*': printf("20 %c 4 = %d\n", op, a*b); break; case '/': printf("20 %c 4 = %d\n", op, a/b); break; default: printf("wrong operator!\n"); break; 15

For Statement The for statement is a convenient way to write a loop that has a counting variable for (expr1; expr2; expr3) statement expr1 is an initialization that is executed only once at the beginning of the loop expr2 is a termination condition expr3 is executed at the end of each loop iteration 16

For Statement (contd.) A for loop that computes the sum of integers from 1 to 100 #include <stdio.h> int main(void) int i, sum = 0; for (i=1; i<=100; i++) sum = sum + i; printf("1 + 2 +... + 99 + 100 = %d\n", sum); return 0; 17

While Statement The while statement has the following form while (expr) statement expr is evaluated If it is true (non-zero), statement is executed and expr is evaluated again This process continues until expr becomes false (zero) 18

While Statement (contd.) Finding the minimum integer i such that 1+2+ + i > 1000 In general, for loops are better if we know the number of iterations in advance, and while loops are better otherwise #include <stdio.h> int main(void) int i = 0, sum = 0; while (sum <= 1000) i = i + 1; sum = sum + i; printf("minimum i which satisfies (1+2+ +i) > 1000 is %d\n", i); return 0; 19

Do While Statement The do while statement is similar to the while statement, but expression is tested after the loop body (i.e., statement) do statement while (expression); the loop body is executed at least once 20

Break Statement Causes an exit from the innermost enclosing loop or switch statement while(1) scanf( %1f, &x); if (x < 0.0) break; printf( %f\n, x*x); 21

Continue Statement Causes the current iteration of a loop to stop and the next iteration of the loop begin Printing all integers less than 100 that are not divisible by 3 #include <stdio.h> int main(void) int i; for (i=0; i<100; i++) if ( i % 3 == 0) continue; printf("%d ", i); printf("\n"); return 0; 22

Arrays An array is a data structure containing a certain number of elements, all of which have the same type To declare an array, specify the type and number of the elements For example, int a[10]; declares a to be an array of 10 integers 23

Arrays (contd.) To access an element of an array, write the array name followed by a subscript In C, subscripts always start with 0 For example, the elements of array a are a[0], a[1],, a[9] 24

Arrays (contd.) An array is initialized by listing the values If the number of values is less than that of the array elements, the remaining elements are given value 0 int a[10] = 9, 8, 7, 6, 5, 4, 3, 2, 1, 0; int a[10] = 0; float a[3] = 0.1, 0.2, 0.0 ; int a[3] = 3, 4 ; int a[] = 2, -4, 1 ; int a[4] = 2, -4, 1 ; char s[] = abcd ; char s[] = a, b, c, d, \0 25

Finding Maximum The program below reads ten values into an array ab and then finds the maximum among the values #include <stdio.h> int main(void) int n, i, max; int ab[10]; printf("enter n: "); scanf("%d", &n); printf("enter n numbers: "); for (i=0; i<n; i++) scanf("%d", &ab[i]); max = ab[0]; for (i=1; i<n; i++) if (ab[i] > max) max = ab[i]; printf("max %d\n", max); return 0; 26

Bubble Sort Sorts array ab of n elements in non-decreasing order The first iteration of the inner for loop brings the maximum element to the last position, the second iteration brings the second maximum to the second-to-last position, etc. The three assignments inside the if statement exchange the values of ab[j] and ab[j+1] 27

Bubble Sort (contd.) for (i=1; i<n; i++) for (j=0; j<n-i; j++) if (ab[j] > ab[j+1]) temp = ab[j]; ab[j] = ab[j+1]; ab[j+1] = temp; 28

Insertion Sort void insertionsort( int a[], int n ) int i, j, val; for( i = 1; i < n; i++) val = a[i]; j = i - 1; while ( ( j >= 0 ) && ( a[j] > val ) ) a[j+1] = a[j]; j--; a[j+1] = val; printintarray( a, n ); 29

Insertion Sort (contd.) #include <stdio.h> #define N 10 void insertionsort( int *, int ); void printintarray( int *, int ); void printintarray( int a[], int n ) int i; for( i = 0; i < n; i++) printf("%4d ", a[i]); int main( void ) int a[n] = 23, -3, 5, 9, 11, 33, 87, -7, -24, 50 ; printintarray( a, N ); insertionsort( a, N ); return 0; printf("\n"); 30

Insertion Sort (contd.) 23-3 5 9 11 33 87-7 -24 50-3 23 5 9 11 33 87-7 -24 50-3 5 23 9 11 33 87-7 -24 50-3 5 9 23 11 33 87-7 -24 50-3 5 9 11 23 33 87-7 -24 50-3 5 9 11 23 33 87-7 -24 50-3 5 9 11 23 33 87-7 -24 50-7 -3 5 9 11 23 33 87-24 50-24 -7-3 5 9 11 23 33 87 50-24 -7-3 5 9 11 23 33 50 87 31

Search Suppose that n elements are stored in an array ab Given a new element x, we want to find if x is in array ab x is one of the elements stored in ab An easy solution for search is to scan the elements in array ab one by one and check if it is equal to x Linear search 32

Linear Search #include <stdio.h> int main(void) int n, i, x; int ab[100]; printf("enter n: "); scanf("%d", &n); printf("enter n numbers: "); for (i=0; i<n; i++) scanf("%d", &ab[i]); printf("enter x: "); scanf("%d", &x); for (i=0; i<n; i++) if (x == ab[i]) printf("%d\n", i); return 0; printf("%d\n", -1); return -1; 33

Binary Search If the elements in array ab are stored in nondecreasing order after sorting, we can solve the search problem more efficiently than linear search We first compare x with the element in the middle (i.e., median) If x is equal to the median, we have found it If x is smaller than the median, we are sure that x is not in the upper part of array ab, so we look for x in the lower part Otherwise, x is larger than the median, we look for x in the upper part Binary search is faster than linear search 34

Binary Search (contd.) low = 0; high = n-1; while (low <= high) mid = (low+high) / 2; if (x < ab[mid]) high = mid 1; else if (x > ab[mid]) low = mid + 1; else printf("%d\n", mid); return 0; printf("%d\n", -1); return -1; 35

Two-dimensional Arrays Two dimensional arrays can be visualized as a multicolumn table or grid or matrix int b[2][5]; Declares a two-dimensional array b that has 2 rows and 5 columns We can initialize a two-dimensional array as follows: int b[2][5] = 1,0,0,1,1,0,0,1,1,1; 36