COMP 208 Computers in Engineering

Similar documents
Computers in Engineering. Moving From Fortran to C Part 2 Michael A. Hawker

Computers in Engineering COMP 208. Roots of a Quadratic in C 10/25/2007. Moving From Fortran to C Part 2 Michael A. Hawker

Computers in Engineering. Moving From Fortran to C Michael A. Hawker

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

Problem Solving and 'C' Programming

Flow Control. CSC215 Lecture

Operators and Expressions:

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

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

C Program. Output. Hi everyone. #include <stdio.h> main () { printf ( Hi everyone\n ); }

Control Statements. If Statement if statement tests a particular condition

UNIT IV 2 MARKS. ( Word to PDF Converter - Unregistered ) FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING

MODULE 2: Branching and Looping

Structured Programming. Dr. Mohamed Khedr Lecture 4

Lecture 6. Statements

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

Computers Programming Course 7. Iulian Năstac

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

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

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Variables and literals

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

Prepared by: Shraddha Modi

Chapter 4. Flow of Control

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

Programming for Electrical and Computer Engineers. Loops

Introduction to C Programming

Lectures 4 and 5 (Julian) Computer Programming: Skills & Concepts (INF-1-CP1) double; float; quadratic equations. Practical 1.

Decision Making and Loops

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Programming and Data Structure

Computer Programming. Decision Making (2) Loops

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

Sudeshna Sarkar Dept. of Computer Science & Engineering. Indian Institute of Technology Kharagpur

Course Outline Introduction to C-Programming

Chapter 4 C Program Control

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

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

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

CS1100 Introduction to Programming

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

Chapter 3 Structured Program Development


CSCI 171 Chapter Outlines

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

Chapter 13 Control Structures

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

Introduction. C provides two styles of flow control:

C Programming Multiple. Choice

Repetition and Loop Statements Chapter 5

Conditional Expressions

Lecture 7 Tao Wang 1

ECET 264 C Programming Language with Applications. C Program Control

Conditionals and Loops

CS313D: ADVANCED PROGRAMMING LANGUAGE

Conditional Statement

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

from Appendix B: Some C Essentials

Pointers and scanf() Steven R. Bagley

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

IECD Institute for Entrepreneurship and Career Development Bharathidasan University, Tiruchirappalli 23.

C Programming Class I

Chapter 5: Control Structures

5. Selection: If and Switch Controls

Expression and Operator

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

2. Numbers In, Numbers Out

DECISION CONTROL AND LOOPING STATEMENTS

3. EXPRESSIONS. It is a sequence of operands and operators that reduce to a single value.

Department of Computer Science

Programming for Engineers Iteration

Lecture 02 Summary. C/Java Syntax 1/14/2009. Keywords Variable Declarations Data Types Operators Statements. Functions

sends the formatted data to the standard output stream (stdout) int printf ( format_string, argument_1, argument_2,... ) ;

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100

UNIT- 3 Introduction to C++

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

UNIT 3 OPERATORS. [Marks- 12]

CSE 5A Final Fall 2006

Lesson #4. Logical Operators and Selection Statements. 4. Logical Operators and Selection Statements - Copyright Denis Hamelin - Ryerson University

Structured Program Development

Unit 3. Operators. School of Science and Technology INTRODUCTION

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

Fundamentals of Computer Programming Using C

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

Chapter 3. Selections

Dept. of CSE, IIT KGP

Outline. Computer programming. Debugging. What is it. Debugging. Hints. Debugging

Data Type Fall 2014 Jinkyu Jeong

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

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

This exam is to be taken by yourself with closed books, closed notes, no calculators.

Control structures in C. Going beyond sequential

C-LANGUAGE CURRICULAM

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

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

M1-R4: Programing and Problem Solving using C (JAN 2019)

Transcription:

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: /* */, // A C program is a collection of functions The main function is the starting point If a function doesn t return anything, the return type should be void Blocks of code are enclosed in { Operators: + - * / % ++ -- I/O operations (scanf/printf) provided by standard library. Header file stdio.h must be included COMP 208 - Lecture 14 2

Another Shorthand Expressions such as i = i+3; x = x*(y+2); Can be rewritten i += 3; x *= (y+2); COMP 208 - Lecture 14 3

Compound assignment In general, expressions of the form: var = var op exp; Can be rewritten in a form that is equivalent (but more efficient to execute): var op = exp; This is called compound assignment. COMP 208 - Lecture 14 4

Operator Precedence ( ) [ ] ->.! - * & sizeof cast ++ -- (right->left) / % + - < <= >= > ==!= & /\ &&?: (right->left) = += -= (right->left), (comma) COMP 208 - Lecture 14 5

If Statements in C Syntax: Other forms: if (expression) statement1 else statement2 if (expression) statement Each of the statement can be a simple statement or a block statement enclosed in { if (expression1) statement else if (expression2) statement... else statement COMP 208 - Lecture 14 6

A Note On Syntax There is no marker to end the if statement Only a single statement can appear in each clause Grouping statements inside braces { makes them into a single compound statement A compound statement (a group of statements in { ) can appear wherever a single statement can appear COMP 208 - Lecture 14 7

examples if (a > 0) b++; = if (a > 0) { b++; recommended! if (a > 0) b++; c++; = if (a > 0) { b++; c++; if (a > 0) { b++; c++; COMP 208 - Lecture 14 8

Nested if Statements The statement executed as a result of an if statement or else clause could be another if statement These are called nested if statements COMP 208 - Lecture 14 9

Min of three int num1, num2; int num3, min = 0;... if (num1 < num2) if (num1 < num3) min = num1; else min = num3; else if (num2 < num3) min = num2; else min = num3; if (num1 < num2) { if (num1 < num3) min = num1; else min = num3; else { if (num2 < num3) min = num2; else min = num3; It is recommended to use { to make the structure clearer. COMP 208 - Lecture 14 10

Wait a Second! There is no logical type in C This isn t like Fortran What is the expression supposed to evaluate to? What is the meaning of an if statement? COMP 208 - Lecture 14 11

Semantics of if Statements 1. Evaluate the expression a) If it evaluates to any non-zero value, execute the first statement b) If it evaluates to 0, execute the else clause, if any. 2. Go on to the statement following the if if (3) printf( true ); else printf( false ); if (3.5) printf( true ); else printf( false ); COMP 208 - Lecture 14 12

From Fortran to C Part 2 Nathan Friedman

Roots of a Quadratic in C #include <stdio.h> #include <math.h> void main() { float a, b, c; float d; float root1, root2; scanf ("%f%f%f", &a, &b, &c); /* continued on next slide */ COMP 208 - Lecture 14 14

if (a == 0.0) if (b == 0.0) if (c == 0.0) printf ("All numbers are roots \n"); else printf ("Unsolvable equation"); else printf ("This is a linear form, root = %f\n", -c/b); else { d = b*b - 4.0*a*c ; if (d > 0.0) { d = sqrt (d); root1 = (-b + d)/(2.0 * a) ; root2 = (-b - d)/(2.0 * a) ; printf ("Roots are %f and %f \n", root1, root2); else if (d == 0.0) else { printf ("The repeated root is %f \n", -b/(2.0 * a)); printf ("There are no real roots \n"); printf ("The discriminant is %f \n", d); COMP 208 - Lecture 14 15

Quadratic Roots Revisited Let s make one slight change to the program: COMP 208 - Lecture 14 16

if (a = 0.0) if (b == 0.0) if (c == 0.0) printf ("All numbers are roots \n"); else printf ("Unsolvable equation"); else printf ("This is a linear form, root = %f\n", -c/b); else { d = b*b - 4.0*a*c ; if (d > 0.0) { d = sqrt (d); root1 = (-b + d)/(2.0 * a) ; root2 = (-b - d)/(2.0 * a) ; printf ("Roots are %f and %f \n", root1, root2); else if (d == 0.0) else { printf ("The repeated root is %f \n", -b/(2.0 * a)); printf ("There are no real roots \n"); printf ("The discriminant is %f \n", d); COMP 208 - Lecture 14 17

Quadratic Roots Revisited Can you spot the change? What do you think the effect is? COMP 208 - Lecture 14 18

What Happens Here? The equivalent statement in Fortran would cause a syntax error The expression (a = 0.0) is not of type logical But C does not have a type logical What happens in C? COMP 208 - Lecture 14 19

The C Assignment Operator In Fortran, assignment is a statement. In C, assignment is an operator COMP 208 - Lecture 14 20

The C Assignment Operator In Fortran, assignment is a statement. In C, assignment is an operator It can appear as part of an expression if ((a = b+c) > d) f++; = a = b+c; if (a > d) f++; When evaluated it causes a value to be assigned (as in Fortran) It also returns a value that can be used in evaluating the expression If it appears independently, with a ; after it this value is discarded COMP 208 - Lecture 14 21

The C Assignment Operator Syntax: variable = expression Semantics 1. Evaluate the expression 2. Store the value in the expression in the variable 3. Return the value to the expression Assignment statement in C has a value (the value of the right-hand side expression). In Fortran, assignment statements have no value. COMP 208 - Lecture 14 22

Back to our example In C, (a=0.0) would assign 0 to a and then return 0 as the value of the expression The if condition, with value 0, would be taken as equivalent to false The else clause would be evaluated and when the root was calculated, there would be an attempt to divide by 0 COMP 208 - Lecture 14 23

? : Conditional operator C has many operators and functions that are not part of Fortran They come in useful in many applications One of these is the?: operator COMP 208 - Lecture 14 24

The? Operator The? (ternary condition) operator is a more efficient form for expressing simple if selection It has the following syntax: e1? e2 : e3 Semantics: e1 is evaluated, if it is true (non-0), the value of the whole expression is e2; otherwise it is e3. COMP 208 - Lecture 14 25

The? Operator To assign the maximum of a and b to z: z = (a>b)? a : b; which is equivalent to: if (a>b) z = a; else z = b; printf( Time = %d %s\n, n, (n==1)? hour : hours ); If n is 1, it prints Time = 1 hour If n is 3, it prints Time = 3 hours COMP 208 - Lecture 14 26

Loops in C The basic looping construct in Fortran is the DO loop In C, there is a more complex looping command called the for loop COMP 208 - Lecture 14 27

The C for Loop The C for statement has the following (deceptively simple) form: for (e1; e2; e3) statement The statement can be a block of statements inside braces { The Fortran equivalent is: e1 DO WHILE(e2) statement e3 END DO or COMP 208 - Lecture 14 28 e1 DO IF (.NOT. e2) EXIT statement e3 END DO

Semantics of the for loop for (e1; e2; e3) statement 1. e1 is evaluated just once before the loop begins. It initializes the loop. 2. e2 is tested at the beginning of each iteration. It is the termination condition. If it evaluates to 0 (false) the loop terminates. Otherwise the loop continues. 3. e3 is evaluated at the end of each iteration. It is used to modify the loop control. It is often a simple increment, but can be more complex. COMP 208 - Lecture 14 29

A C for Loop Example main(){ int x; for (x=3; x>0; x--) printf("x=%d\n",x);...outputs: x=3 x=2 x=1 COMP 208 - Lecture 14 30

What do these do? for (i=1; i<10; i++) printf( %d %d %d\n, i, i*i, i*i*i); 1 1 1 2 4 8 3 9 27... 9 81 729 for (x=3; ((x>3) && (x<9)); x++) for (x=3,y=4; ((x>=3) && (y<9)); x++,y+=2) printf( yes ); for (x=0,y=4,z=4000; z; z/=10) Comma operator COMP 208 - Lecture 14 31

The While Statement The while has the syntax: while (expression) statement Semantics: The expression is evaluated. If it evaluates to 0 (false) the loop terminates, otherwise the statement is executed and we repeat the evaluation. COMP 208 - Lecture 14 32

Example main() { int x=3; while (x>0) { printf("x=%d\n",x); x--;...outputs: x=3 x=2 x=1 COMP 208 - Lecture 14 33

While Statements The equivalence of a for loop and a while loop for(e1; e2; e3) statement The while statement while (e) s is semantically equivalent to for (;e;) s e1; while(e2) { statement e3 COMP 208 - Lecture 14 34

for vs. while Using Fortran parlance, for a definite iterator, we normally use the for loop For an indefinite iterator, we normally use the while loop. COMP 208 - Lecture 14 35

What do these do? As with many constructs in C, the while statement can interact with other features to become much less clear: while (x--) ; while (x=x+1) ; while (x+=5) ; while (i++ < 10) ; while (x--!= 0) while ((x=x+1)!= 0) while ( (ch = getchar())!= q ) putchar(ch); COMP 208 - Lecture 14 36

Do-while Both while and do-while execute a statement repeatedly and terminate when a condition becomes false In the do-while, the testing is done at the end of the loop do statement while (expression) Therefore, the loop body is executed at least once. COMP 208 - Lecture 14 37

Break and Continue The break statement is similar to the Fortran EXIT and allows us to exit from a loop break; --exit from loop The continue statement forces control back to the top of the loop continue; --skip 1 iteration of loop COMP 208 - Lecture 14 38

Using break and continue while (scanf( %d, &value ) == 1 && value!= 0) { if (value < 0) { printf( Illegal value\n ); break; /* Abandon the loop */ if (value > 100) { printf( Invalid value\n ); continue; /* Skip to start loop again */ /* Process the value (guaranteed between 1 and 100) */...; /* end while when value read is 0 */ COMP 208 - Lecture 14 39

Inputting Values in C In the program for computing the roots of a quadratic, we began by reading the values for the coefficients a, b and c COMP 208 - Lecture 14 40

Roots of a Quadratic in C #include <stdio.h> #include <math.h> void main() { float a, b, c; float d; float root1, root2; scanf ("%f%f%f", &a, &b, &c); /* continued on next slide */ COMP 208 - Lecture 14 41

The Input Statement Syntax: scanf( format string, list of variable references) ; Semantics: Each variable reference is has the form &name For now, ignore the & that appears in front of variable names It has to be there but we ll explain why later The & is the address of operator. So, &a is the address of the variable a. COMP 208 - Lecture 14 42

parameter passing in C In C, function parameters are passed in a way known as pass by value. The default way in Fortran is pass by reference. void fun(int x) { x = x+1; int main() { int i = 1; fun(i); printf( %d\n, i); If this were Fortran, i would be changed to 2. NOT in C though. void fun(int *x) { *x = *x+1; int main() { int i = 1; fun(&i); printf( %d\n, i); In C, we have to pass the address of the variable COMP 208 - Lecture 14 43