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

Size: px
Start display at page:

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

Transcription

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

2 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

3 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

4 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

5 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

6 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

7 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

8 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

9 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

10 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

11 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

12 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

13 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

14 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

15 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

16 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

17 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(" = %d\n", sum); return 0; 17

18 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

19 While Statement (contd.) Finding the minimum integer i such that 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

20 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

21 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

22 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

23 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

24 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

25 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

26 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

27 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

28 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

29 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

30 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

31 Insertion Sort (contd.)

32 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

33 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

34 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

35 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

36 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

Arrays and Applications

Arrays and Applications Arrays and Applications 60-141: Introduction to Algorithms and Programming II School of Computer Science Term: Summer 2014 Instructor: Dr. Asish Mukhopadhyay What s an array Let a 0, a 1,, a n-1 be a sequence

More information

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

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions. Introduction In the programs that we have dealt with so far, all statements inside the main function were executed in sequence as they appeared, one after the other. This type of sequencing is adequate

More information

Programming for Electrical and Computer Engineers. Loops

Programming for Electrical and Computer Engineers. Loops Programming for Electrical and Computer Engineers Loops Dr. D. J. Jackson Lecture 6-1 Iteration Statements C s iteration statements are used to set up loops. A loop is a statement whose job is to repeatedly

More information

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

UNIVERSITY OF WINDSOR Fall 2007 QUIZ # 2 Solution. Examiner : Ritu Chaturvedi Dated :November 27th, Student Name: Student Number: UNIVERSITY OF WINDSOR 60-106-01 Fall 2007 QUIZ # 2 Solution Examiner : Ritu Chaturvedi Dated :November 27th, 2007. Student Name: Student Number: INSTRUCTIONS (Please Read Carefully) No calculators allowed.

More information

Lecture 6 Sorting and Searching

Lecture 6 Sorting and Searching Lecture 6 Sorting and Searching Sorting takes an unordered collection and makes it an ordered one. 1 2 3 4 5 6 77 42 35 12 101 5 1 2 3 4 5 6 5 12 35 42 77 101 There are many algorithms for sorting a list

More information

Flow Control. CSC215 Lecture

Flow Control. CSC215 Lecture Flow Control CSC215 Lecture Outline Blocks and compound statements Conditional statements if - statement if-else - statement switch - statement? : opertator Nested conditional statements Repetitive statements

More information

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

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee C Language Part 1 (Minor modifications by the instructor) References C for Python Programmers, by Carl Burch, 2011. http://www.toves.org/books/cpy/ The C Programming Language. 2nd ed., Kernighan, Brian,

More information

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

Indian Institute of Technology Kharagpur Programming and Data Structures (CS10001) Autumn : Mid-Semester Examination Indian Institute of Technology Kharagpur Programming and Data Structures (CS10001) Autumn 2017-18: Mid-Semester Examination Time: 2 Hours Full Marks: 60 INSTRUCTIONS 1. Answer ALL questions 2. Please write

More information

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

공학프로그래밍언어 (PROGRAMMING LANGUAGE FOR ENGINEERS) -CONTROL FLOW : LOOP- SPRING 2015, SEON-JU AHN, CNU EE 공학프로그래밍언어 (PROGRAMMING LANGUAGE FOR ENGINEERS) -CONTROL FLOW : LOOP- SPRING 2015, SEON-JU AHN, CNU EE LOOPS WHILE AND FOR while syntax while (expression) statement The expression is evaluated. If it is

More information

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

Chapter 6. Loops. Iteration Statements. C s iteration statements are used to set up loops. Chapter 6 Loops 1 Iteration Statements C s iteration statements are used to set up loops. A loop is a statement whose job is to repeatedly execute some other statement (the loop body). In C, every loop

More information

Computer Science & Engineering 150A Problem Solving Using Computers

Computer Science & Engineering 150A Problem Solving Using Computers Computer Science & Engineering 150A Problem Solving Using Computers Lecture 06 - Stephen Scott Adapted from Christopher M. Bourke 1 / 30 Fall 2009 Chapter 8 8.1 Declaring and 8.2 Array Subscripts 8.3 Using

More information

Principles of Programming. Chapter 6: Arrays

Principles of Programming. Chapter 6: Arrays Chapter 6: Arrays In this chapter, you will learn about Introduction to Array Array declaration Array initialization Assigning values to array elements Reading values from array elements Simple Searching

More information

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

COP 3223 Introduction to Programming with C - Study Union - Fall 2017 COP 3223 Introduction to Programming with C - Study Union - Fall 2017 Chris Marsh and Matthew Villegas Contents 1 Code Tracing 2 2 Pass by Value Functions 4 3 Statically Allocated Arrays 5 3.1 One Dimensional.................................

More information

Introduction to Computer Science Midterm 3 Fall, Points

Introduction to Computer Science Midterm 3 Fall, Points Introduction to Computer Science Fall, 2001 100 Points Notes 1. Tear off this sheet and use it to keep your answers covered at all times. 2. Turn the exam over and write your name next to the staple. Do

More information

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

Statements. Control Flow Statements. Relational Operators. Logical Expressions. Relational Operators. Relational Operators 1/30/14 Statements Control Flow Statements Based on slides from K. N. King Bryn Mawr College CS246 Programming Paradigm So far, we ve used return statements and expression statements. Most of C s remaining statements

More information

DECISION MAKING STATEMENTS

DECISION MAKING STATEMENTS DECISION MAKING STATEMENTS If, else if, switch case These statements allow the execution of selective statements based on certain decision criteria. C language provides the following statements: if statement

More information

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

n Group of statements that are executed repeatedly while some condition remains true Looping 1 Loops n Group of statements that are executed repeatedly while some condition remains true n Each execution of the group of statements is called an iteration of the loop 2 Example counter 1,

More information

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

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #16 Loops: Matrix Using Nested for Loop In this section, we will use the, for loop to code of the matrix problem.

More information

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

Introduction to Computing Lecture 07: Repetition and Loop Statements (Part II) Introduction to Computing Lecture 07: Repetition and Loop Statements (Part II) Assist.Prof.Dr. Nükhet ÖZBEK Ege University Department of Electrical & Electronics Engineering nukhet.ozbek@ege.edu.tr Topics

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

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

Chapter 4: Expressions. Chapter 4. Expressions. Copyright 2008 W. W. Norton & Company. All rights reserved. Chapter 4: Expressions Chapter 4 Expressions 1 Chapter 4: Expressions Operators Expressions are built from variables, constants, and operators. C has a rich collection of operators, including arithmetic

More information

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

COP 3223 Introduction to Programming with C - Study Union - Spring 2018 COP 3223 Introduction to Programming with C - Study Union - Spring 2018 Chris Marsh and Matthew Villegas Contents 1 Code Tracing 2 2 Pass by Value Functions 4 3 Statically Allocated Arrays 5 3.1 One Dimensional.................................

More information

16.216: ECE Application Programming Fall 2011

16.216: ECE Application Programming Fall 2011 16.216: ECE Application Programming Fall 2011 Exam 2 Solution 1. (24 points, 6 points per part) Multiple choice For each of the multiple choice questions below, clearly indicate your response by circling

More information

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

Flow of Control. Selection. if statement. True and False in C False is represented by any zero value. switch Flow of Control True and False in C Conditional Execution Iteration Nested Code(Nested-ifs, Nested-loops) Jumps 1 True and False in C False is represented by any zero value The int expression having the

More information

Programming for Engineers Iteration

Programming for Engineers Iteration Programming for Engineers Iteration ICEN 200 Spring 2018 Prof. Dola Saha 1 Data type conversions Grade average example,-./0 class average = 23450-67 893/0298 Grade and number of students can be integers

More information

EECE.2160: ECE Application Programming Spring 2018

EECE.2160: ECE Application Programming Spring 2018 EECE.2160: ECE Application Programming Spring 2018 1. (46 points) C input/output; operators Exam 1 Solution a. (13 points) Show the output of the short program below exactly as it will appear on the screen.

More information

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

Sample Examination. Family Name:... Other Names:... Signature:... Student Number:... Family Name:... Other Names:... Signature:... Student Number:... THE UNIVERSITY OF NEW SOUTH WALES SCHOOL OF COMPUTER SCIENCE AND ENGINEERING Sample Examination COMP1917 Computing 1 EXAM DURATION: 2 HOURS

More information

Functions. Chapter 5

Functions. Chapter 5 Functions Chapter 5 Function Definition type function_name ( parameter list ) declarations statements For example int factorial(int n) int i, product = 1; for (i = 2; I

More information

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

CSE101-Lec#18. Multidimensional Arrays Application of arrays. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming CSE101-Lec#18 Multidimensional Arrays Application of arrays Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU Outline Defining and processing 1D array 2D array Applications of arrays 1-D array A

More information

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

Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011 Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011 Autumn 2015 Lecture 3, Simple C programming M. Eriksson (with contributions from A. Maki and

More information

Module 6: Array in C

Module 6: Array in C 1 Table of Content 1. Introduction 2. Basics of array 3. Types of Array 4. Declaring Arrays 5. Initializing an array 6. Processing an array 7. Summary Learning objectives 1. To understand the concept of

More information

Lecture 6. Statements

Lecture 6. Statements Lecture 6 Statements 1 Statements This chapter introduces the various forms of C++ statements for composing programs You will learn about Expressions Composed instructions Decision instructions Loop instructions

More information

COMP 208 Computers in Engineering

COMP 208 Computers in Engineering COMP 208 Computers in Engineering Lecture 14 Jun Wang School of Computer Science McGill University Fall 2007 COMP 208 - Lecture 14 1 Review: basics of C C is case sensitive 2 types of comments: /* */,

More information

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

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size]; Arrays An array is a collection of two or more adjacent memory cells, called array elements. Array is derived data type that is used to represent collection of data items. C Array is a collection of data

More information

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

ECE15: Introduction to Computer Programming Using the C Language. Lecture Unit 4: Flow of Control ECE15: Introduction to Computer Programming Using the C Language Lecture Unit 4: Flow of Control Outline of this Lecture Examples of Statements in C Conditional Statements The if-else Conditional Statement

More information

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

Programming & Data Structure Laboratory. Arrays, pointers and recursion Day 5, August 5, 2014 Programming & Data Structure Laboratory rrays, pointers and recursion Day 5, ugust 5, 2014 Pointers and Multidimensional rray Function and Recursion Counting function calls in Fibonacci #include

More information

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

COP 3223 Introduction to Programming with C - Study Union - Fall 2017 COP 3223 Introduction to Programming with C - Study Union - Fall 2017 Chris Marsh and Matthew Villegas Contents 1 Code Tracing 2 2 Pass by Value Functions 4 3 Statically Allocated Arrays 5 3.1 One Dimensional.................................

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

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

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University ITC213: STRUCTURED PROGRAMMING Bhaskar Shrestha National College of Computer Studies Tribhuvan University Lecture 08: Control Statements Readings: Chapter 6 Control Statements and Their Types A control

More information

Decision Making -Branching. Class Incharge: S. Sasirekha

Decision Making -Branching. Class Incharge: S. Sasirekha Decision Making -Branching Class Incharge: S. Sasirekha Branching The C language programs presented until now follows a sequential form of execution of statements. Many times it is required to alter the

More information

Dept. of CSE, IIT KGP

Dept. of CSE, IIT KGP Control Flow: Looping CS10001: Programming & Data Structures Pallab Dasgupta Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur Types of Repeated Execution Loop: Group of

More information

Chapter 4. Flow of Control

Chapter 4. Flow of Control Chapter 4. Flow of Control Byoung-Tak Zhang TA: Hanock Kwak Biointelligence Laboratory School of Computer Science and Engineering Seoul National Univertisy http://bi.snu.ac.kr Sequential flow of control

More information

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

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators Expressions 1 Expressions n Variables and constants linked with operators Arithmetic expressions n Uses arithmetic operators n Can evaluate to any value Logical expressions n Uses relational and logical

More information

Module 4: Decision-making and forming loops

Module 4: Decision-making and forming loops 1 Module 4: Decision-making and forming loops 1. Introduction 2. Decision making 2.1. Simple if statement 2.2. The if else Statement 2.3. Nested if Statement 3. The switch case 4. Forming loops 4.1. The

More information

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

Programming & Data Structure Laboratory. Day 2, July 24, 2014 Programming & Data Structure Laboratory Day 2, July 24, 2014 Loops Pre and post test loops for while do-while switch-case Pre-test loop and post-test loop Condition checking True Loop Body False Loop Body

More information

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

CS Introduction to Programming Midterm Exam #2 - Prof. Reed Fall 2015 CS 141 - Introduction to Programming Midterm Exam #2 - Prof. Reed Fall 2015 You may take this test with you after the test, but you must turn in your answer sheet. This test has the following sections:

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

Programming for Electrical and Computer Engineers. Pointers and Arrays

Programming for Electrical and Computer Engineers. Pointers and Arrays Programming for Electrical and Computer Engineers Pointers and Arrays Dr. D. J. Jackson Lecture 12-1 Introduction C allows us to perform arithmetic addition and subtraction on pointers to array elements.

More information

Introduction. C provides two styles of flow control:

Introduction. C provides two styles of flow control: Introduction C provides two styles of flow control: Branching Looping Branching is deciding what actions to take and looping is deciding how many times to take a certain action. Branching constructs: if

More information

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

Pointers. Pointer Variables. Chapter 11. Pointer Variables. Pointer Variables. Pointer Variables. Declaring Pointer Variables Chapter 11 Pointers The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into bytes, with each byte capable

More information

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

Functions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur Functions CS10001: Programming & Data Structures Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur 1 Recursion A process by which a function calls itself

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

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

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU CSE101-lec#12 Designing Structured Programs Introduction to Functions Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU Outline Designing structured programs in C: Counter-controlled repetition

More information

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

only in the space provided. Do the rough work in the space provided for it. The question paper has total 12 pages. Instructions: Answer all five questions. Total marks = 10 x 2 + 4 x 10 = 60. Time = 2hrs. Write your answer only in the space provided. Do the rough work in the space provided for it. The question paper

More information

CSCI 2132 Software Development. Lecture 19: Generating Permutations

CSCI 2132 Software Development. Lecture 19: Generating Permutations CSCI 2132 Software Development Lecture 19: Generating Permutations Instructor: Vlado Keselj Faculty of Computer Science Dalhousie University 19-Oct-2018 (19) CSCI 2132 1 Previous Lecture Mergesort implementation

More information

CSE 130 Introduction to Programming in C Control Flow Revisited

CSE 130 Introduction to Programming in C Control Flow Revisited CSE 130 Introduction to Programming in C Control Flow Revisited Spring 2018 Stony Brook University Instructor: Shebuti Rayana Control Flow Program Control Ø Program begins execution at the main() function.

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

Structured programming Exercises 6 Version 1.0, 25 October, 2016 Table of Contents 1. Arrays []................................................................... 1 1.1. Declaring arrays.........................................................

More information

Problem Solving and 'C' Programming

Problem Solving and 'C' Programming Problem Solving and 'C' Programming Targeted at: Entry Level Trainees Session 05: Selection and Control Structures 2007, Cognizant Technology Solutions. All Rights Reserved. The information contained herein

More information

C: How to Program. Week /Mar/05

C: How to Program. Week /Mar/05 1 C: How to Program Week 2 2007/Mar/05 Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers

More information

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

CSE101-lec#19. Array searching and sorting techniques. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming CSE101-lec#19 Array searching and sorting techniques Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU Outline Introduction Linear search Binary search Bubble sort Introduction The process of finding

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

One Dimension Arrays 1

One Dimension Arrays 1 One Dimension Arrays 1 Array n Many applications require multiple data items that have common characteristics In mathematics, we often express such groups of data items in indexed form: n x 1, x 2, x 3,,

More information

Control Flow, Functions and Basic Linkage

Control Flow, Functions and Basic Linkage Control Flow, Functions and Basic Linkage MATH 5061: Fundamentals of Computer Programming for Scientists and Engineers Dr. Richard Berger richard.berger@temple.edu Department of Mathematics Temple University

More information

Lecture 3. More About C

Lecture 3. More About C Copyright 1996 David R. Hanson Computer Science 126, Fall 1996 3-1 Lecture 3. More About C Programming languages have their lingo Programming language Types are categories of values int, float, char Constants

More information

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

Lecture 2. Examples of Software. Programming and Data Structure. Programming Languages. Operating Systems. Sudeshna Sarkar Examples of Software Programming and Data Structure Lecture 2 Sudeshna Sarkar Read an integer and determine if it is a prime number. A Palindrome recognizer Read in airline route information as a matrix

More information

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

CMPE-013/L. Introduction to C Programming. Unit testing CMPE-013/L Introduction to C Programming Gabriel Hugh Elkaim Winter 2015 Example Unit testing Testing architecture // Declare test constants testinput some input testexpoutput precalculated output // Calculate

More information

Solutions to Chapter 8

Solutions to Chapter 8 Solutions to Chapter 8 Review Questions 1. a. True 3. b. False 5. b. False 7. c. index 9. d. ary[0] = x; 11. e. sorting 13. e. sequential 15. a. A two-dimensional array can be thought of as an array of

More information

Arrays and Strings. Arash Rafiey. September 12, 2017

Arrays and Strings. Arash Rafiey. September 12, 2017 September 12, 2017 Arrays Array is a collection of variables with the same data type. Arrays Array is a collection of variables with the same data type. Instead of declaring individual variables, such

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

Engineering program development 6. Edited by Péter Vass

Engineering program development 6. Edited by Péter Vass Engineering program development 6 Edited by Péter Vass Variables When we define a variable with its identifier (name) and type in the source code, it will result the reservation of some memory space for

More information

C Programming Lecture V

C Programming Lecture V C Programming Lecture V Instructor Özgür ZEYDAN http://cevre.beun.edu.tr/ Modular Programming A function in C is a small sub-program that performs a particular task, and supports the concept of modular

More information

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

Day05 A. Young W. Lim Sat. Young W. Lim Day05 A Sat 1 / 14 Day05 A Young W. Lim 2017-10-07 Sat Young W. Lim Day05 A 2017-10-07 Sat 1 / 14 Outline 1 Based on 2 Structured Programming (2) Conditions and Loops Conditional Statements Loop Statements Type Cast Young

More information

Storage class and Scope:

Storage class and Scope: Algorithm = Logic + Control + Data Data structures and algorithms Data structures = Ways of systematically arranging information, both abstractly and concretely Algorithms = Methods for constructing, searching,

More information

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

Unit 1 - Arrays. 1 What is an array? Explain with Example. What are the advantages of using an array? 1 What is an array? Explain with Example. What are the advantages of using an array? An array is a fixed-size sequenced collection of elements of the same data type. An array is derived data type. The

More information

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

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University ITC213: STRUCTURED PROGRAMMING Bhaskar Shrestha National College of Computer Studies Tribhuvan University Lecture 10: Arrays Readings: Chapter 9 Introduction Group of same type of variables that have same

More information

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

Slide Set 1. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary Slide Set 1 for ENCM 339 Fall 2016 Steve Norman, PhD, PEng Electrical & Computer Engineering Schulich School of Engineering University of Calgary September 2016 ENCM 339 Fall 2016 Slide Set 1 slide 2/43

More information

The C language. Introductory course #1

The C language. Introductory course #1 The C language Introductory course #1 History of C Born at AT&T Bell Laboratory of USA in 1972. Written by Dennis Ritchie C language was created for designing the UNIX operating system Quickly adopted

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

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

Comments. Comments: /* This is a comment */ Flow Control Comments Comments: /* This is a comment */ Use them! Comments should explain: special cases the use of functions (parameters, return values, purpose) special tricks or things that are not

More information

PROGRAMMING IN C LAB MANUAL FOR DIPLOMA IN ECE/EEE

PROGRAMMING IN C LAB MANUAL FOR DIPLOMA IN ECE/EEE PROGRAMMING IN C LAB MANUAL FOR DIPLOMA IN ECE/EEE 1. Write a C program to perform addition, subtraction, multiplication and division of two numbers. # include # include int a, b,sum,

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 8 Array typical problems, Search, Sorting Department of Computer Engineering Outline

More information

Chapter 7 Functions. Now consider a more advanced example:

Chapter 7 Functions. Now consider a more advanced example: Chapter 7 Functions 7.1 Chapter Overview Functions are logical groupings of code, a series of steps, that are given a name. Functions are especially useful when these series of steps will need to be done

More information

INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Stamp / Signature of the Invigilator

INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Stamp / Signature of the Invigilator INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Stamp / Signature of the Invigilator EXAMINATION ( End Semester ) SEMESTER ( Spring ) Roll Number Section Name Subject Number C S 1 0 0 0 1 Subject Name Programming

More information

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

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) Introduction to arrays CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) Introduction to arrays 1 What are Arrays? Arrays are our first example of structured data. Think of a book with pages numbered 1,2,...,400.

More information

Computer Programming Lecture 14 Arrays (Part 2)

Computer Programming Lecture 14 Arrays (Part 2) Computer Programming Lecture 14 Arrays (Part 2) Assist.Prof.Dr. Nükhet ÖZBEK Ege University Department of Electrical & Electronics Engineering nukhet.ozbek@ege.edu.tr 1 Topics The relationship between

More information

UIC. C Programming Primer. Bharathidasan University

UIC. C Programming Primer. Bharathidasan University C Programming Primer UIC C Programming Primer Bharathidasan University Contents Getting Started 02 Basic Concepts. 02 Variables, Data types and Constants...03 Control Statements and Loops 05 Expressions

More information

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

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University Overview of C, Part 2 CSE 130: Introduction to Programming in C Stony Brook University Integer Arithmetic in C Addition, subtraction, and multiplication work as you would expect Division (/) returns the

More information

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

FORM 2 (Please put your name and form # on the scantron!!!!) CS 161 Exam 2: FORM 2 (Please put your name and form # on the scantron!!!!) True (A)/False(B) (2 pts each): 1. Recursive algorithms tend to be less efficient than iterative algorithms. 2. A recursive function

More information

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

Make sure the version number is marked on your scantron sheet. This is Version 1 Last Name First Name McGill ID Make sure the version number is marked on your scantron sheet. This is Version 1 McGill University COMP 208 -- Computers in Engineering Mid-Term Examination Tuesday, March

More information

Structured programming. Exercises 3

Structured programming. Exercises 3 Exercises 3 Table of Contents 1. Reminder from lectures...................................................... 1 1.1. Relational operators..................................................... 1 1.2. Logical

More information

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

Chapter 12: Pointers and Arrays. Chapter 12. Pointers and Arrays. Copyright 2008 W. W. Norton & Company. All rights reserved. Chapter 12 Pointers and Arrays 1 Introduction C allows us to perform arithmetic addition and subtraction on pointers to array elements. This leads to an alternative way of processing arrays in which pointers

More information

Sorting & Searching. Hours: 10. Marks: 16

Sorting & Searching. Hours: 10. Marks: 16 Sorting & Searching CONTENTS 2.1 Sorting Techniques 1. Introduction 2. Selection sort 3. Insertion sort 4. Bubble sort 5. Merge sort 6. Radix sort ( Only algorithm ) 7. Shell sort ( Only algorithm ) 8.

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 28, 2008 12:20 p.m. 1:50 p.m. Examiners: Jason Anderson, Tom Fairgrieve, Baochun

More information

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

Week 2 / Lecture 2 15 March 2017 NWEN 241 Control constructs, Functions. Alvin Valera Week 2 / Lecture 2 15 March 2017 NWEN 241 Control constructs, Functions Alvin Valera School of Engineering and Computer Science Victoria University of Wellington Admin stuff Tutorial #2 Expectations on

More information

Programming Language A

Programming Language A Programming Language A Takako Nemoto (JAIST) 22 October Takako Nemoto (JAIST) 22 October 1 / 28 From Homework 2 Homework 2 1 Write a program calculate something with at least two integer-valued inputs,

More information

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 7

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 7 Strings and Clases BIL104E: Introduction to Scientific and Engineering Computing Lecture 7 Manipulating Strings Scope and Storage Classes in C Strings Declaring a string The length of a string Copying

More information

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

C/Java Syntax. January 13, Slides by Mark Hancock (adapted from notes by Craig Schock) C/Java Syntax 1 Lecture 02 Summary Keywords Variable Declarations Data Types Operators Statements if, switch, while, do-while, for Functions 2 By the end of this lecture, you will be able to identify the

More information

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

C/Java Syntax. Lecture 02 Summary. Keywords Variable Declarations Data Types Operators Statements. Functions. if, switch, while, do-while, for C/Java Syntax 1 Lecture 02 Summary Keywords Variable Declarations Data Types Operators Statements if, switch, while, do-while, for Functions 2 1 By the end of this lecture, you will be able to identify

More information

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

Functions. (transfer of parameters, returned values, recursion, function pointers). Functions (transfer of parameters, returned values, recursion, function pointers). A function is a named, independent section of C/C++ code that performs a specific task and optionally returns a value

More information