Beginning C Programming for Engineers

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

Chapter 4: Basic C Operators

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

C Functions. 5.2 Program Modules in C

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

CSI31 Lecture 5. Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial

ANSI C Programming Simple Programs

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

Chapter 2. Outline. Simple C++ Programs

ECET 264 C Programming Language with Applications

Programming for Engineers Functions

Expressions. Eric McCreath

CSE123. Program Design and Modular Programming Functions 1-1

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

Operators and Expression. Dr Muhamad Zaini Yunos JKBR, FKMP

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

Computer Science & Engineering 150A Problem Solving Using Computers

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

C Programs: Simple Statements and Expressions

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 3. Existing Information. Notes. Notes. Notes. Lecture 03 - Functions

C++ Programming Lecture 11 Functions Part I

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

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

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

Functions. Systems Programming Concepts

Introduction to Engineering gii

Chapter 3. Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus. Existing Information.

Outline. Performing Computations. Outline (cont) Expressions in C. Some Expression Formats. Types for Operands

Lecture 3. More About C

Python Programming: An Introduction to Computer Science

Standard Library Functions Outline

Chapter 5 C Functions

Function Call Stack and Activation Records

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

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

Chapter 3 Structure of a C Program

CS3157: Advanced Programming. Outline

Lecture 04 FUNCTIONS AND ARRAYS

Structured Programming. Dr. Mohamed Khedr Lecture 4

Beginning C Programming for Engineers

Chapter 4 Expression & Operators

Summary of basic C++-commands

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

AMS 27L LAB #1 Winter 2009

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

C++ Overview. Chapter 1. Chapter 2

Operators & Expressions

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

C Program Structures

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

MA 511: Computer Programming Lecture 3: Partha Sarathi Mandal

ISA 563 : Fundamentals of Systems Programming

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

LESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long

PROGRAMMING WITH MATLAB DR. AHMET AKBULUT

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

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

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

Part V Appendices c Copyright, Todd Young and Martin Mohlenkamp, Department of Mathematics, Ohio University, 2017

Goals for This Lecture:

Operators and Expressions:

C: How to Program. Week /Mar/05

Ordinary Differential Equation Solver Language (ODESL) Reference Manual

Fundamentals of Programming & Procedural Programming

C Syntax Arrays and Loops Math Strings Structures Pointers File I/O. Final Review CS Prof. Jonathan Ventura. Prof. Jonathan Ventura Final Review

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

C Functions Pearson Education, Inc. All rights reserved.

Operators. Lecture 3 COP 3014 Spring January 16, 2018

Product Price Formula extension for Magento2. User Guide

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types

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

3.1. Chapter 3: The cin Object. Expressions and Interactivity

An Introduction to C Through Annotated Examples

Programming for Engineers Iteration

Chapter 2 - Introduction to C Programming

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

Expression and Operator

Introduction to Python, Cplex and Gurobi

Calling Prewritten Functions in C

ECET 264 C Programming Language with Applications. C Program Control

Functions and Recursion

Introduction to C++ Introduction and History. Characteristics of C++

Arithmetic Expressions Lesson #1 Outline

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

Operators. Java operators are classified into three categories:

Introduction to Programming

Introduction to Matlab

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

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

Chapter 3. Section 3.10 Type of Expressions and Automatic Conversion. CS 50 Hathairat Rattanasook

Engineering Problem Solving with C++, Etter/Ingber

Data Type Fall 2014 Jinkyu Jeong

H192 Midterm 1 Review. Tom Zajdel

CS1010E Lecture 3 Simple C Programs Part 2

CT 229 Java Syntax Continued

Introduction to MATLAB

Methods CSC 121 Fall 2014 Howard Rosenthal

In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability. programs into their various phases.

PIC 10A. Lecture 3: More About Variables, Arithmetic, Casting, Assignment

2. Numbers In, Numbers Out

Transcription:

Beginning Programming for Engineers R. Lindsay Todd Lecture 2: onditionals, Logic, and Repetition R. Lindsay Todd () Beginning Programming for Engineers Beg 2 1 / 50

Outline Outline 1 Math Operators 2 Random Numbers 3 oin Toss Program 4 The if Statement Relational Operators The if-else Statement hained if-else Statements Logical Operators 5 The while Statement Powers of 2 Program R. Lindsay Todd () Beginning Programming for Engineers Beg 2 2 / 50

Math operators in Math Operators + addition - subtraction * multiplication / division % modulus (remainder) unary + unary - negate Normal order of operations is followed (modulus same as division). Parentheses can be used. If one operand is floating point and the other integer, the integer value is promoted to floating point. Division is integer division if both operands are integers. R. Lindsay Todd () Beginning Programming for Engineers Beg 2 3 / 50

Sample: Operators Math Operators Program: operators.c /* Expressions */ # include <stdio.h> int main () { printf (" 7+3=% d\n", 7+3); printf (" 7-3=% d\n", 7-3); printf (" 7*3=% d\n", 7*3); printf (" 7/3=% d\n", 7/3); printf (" 7%%3=% d\n", 7%3); printf (" 7.0/3.0=% g\n", 7.0/3.0); printf (" Lies! 7+3=% d\n", 42); Results 7+3=10 7-3=4 7*3=21 7/3=2 7%3=1 7.0/3.0=2.33333 Lies! 7+3=42 return 0; R. Lindsay Todd () Beginning Programming for Engineers Beg 2 5 / 50

Type onversions Math Operators Some type conversions are done implicitly: float a = 10.5, b; int c; b = 3 * a; c = b; Explicit type conversions can be done through a cast: float a = 10.5, b; b = ( int ) (3* a); A cast is a type name, in parenthesis, preceding an expression. R. Lindsay Todd () Beginning Programming for Engineers Beg 2 7 / 50

Math functions Math Operators These all require math.h header file. cos(x) cos x sin(x) sin x pow(x,y) x y tan(x) tan x sqrt(x) x acos(x) arccos x exp(x) ɛ x asin(x) arcsin x log(x) ln x atan(x) arctan x log10(x) log 10 x atan2(y,x) arctan y x When using the trigonometric functions, remember that angles are always expressed as radians. R. Lindsay Todd () Beginning Programming for Engineers Beg 2 8 / 50

Math Operators Using Trigonometric Functions Program: trigfunc.c # include <stdio.h> # include <math.h> int main () { float th; /* Theta, angle in radians */ float sum ; printf (" Enter angle Theta in radians : "); scanf ("%g", &th ); sum = sin (th )* sin (th) + cos (th )* cos (th ); printf ("sin - squared + cos - squared = %g\n", sum ); return 0; ompile: gcc -ansi -pedantic -Wall trig.c -lm Results Enter angle Theta in radians: 23 sin-squared + cos-squared = 1 R. Lindsay Todd () Beginning Programming for Engineers Beg 2 10 / 50

Random Numbers Random Numbers Random numbers use the rand function, defined in the stdlib.h header file. r = rand () / ( float ) RAND_MAX ; ri = 1 + rand () % I; The random seed can be set using srand. A good seed is the time function, defined in the time.h header file. srand ( time ( NULL )); R. Lindsay Todd () Beginning Programming for Engineers Beg 2 12 / 50

Random Numbers Example: Random Numbers Program: random.c /* Program to print random numbers in range 1 - -100. */ # include <stdio.h> # include <stdlib.h> # include <time.h> int main () { srand ( time ( NULL )); printf (" Random number : %d\n", 1+ rand ()%100); return 0; Some example runs of this program: Results Random number: 68 Results Random number: 19 R. Lindsay Todd () Beginning Programming for Engineers Beg 2 14 / 50

oin Toss Program Problem: Simulate a coin toss We would like to simulate the computer tossing a coin and telling us if our call is correct or not. Algorithm: 1 Randomly choose heads or tails. 2 Prompt human to call 3 Get the human s call. 4 ompare the call to our choice, and say if the call was right. 5 Stop. This requires our program to make a decision! R. Lindsay Todd () Beginning Programming for Engineers Beg 2 15 / 50

oin Toss Program Diagramming an Algorithm start 1 Randomly choose heads or tails. 2 Prompt human to call 3 Get the human s call. 4 ompare the call to our choice, and say if the call was right. 5 Stop. hoose heads or tails Prompt human to call Get human s call coin = guess No Print message end R. Lindsay Todd () Beginning Programming for Engineers Beg 2 16 / 50

The if Statement The if Statement start hoose heads or tails Prompt human to call Get human s call Execute statement if expression is true (not zero). coin = guess No Print message /* Previous statements */ if (expression ) statement /* Following statements */ end R. Lindsay Todd () Beginning Programming for Engineers Beg 2 18 / 50

Relational Operators The if Statement Relational Operators Besides arithmetic operators, has relational operators which return 1 if the condition is true, or 0 otherwise. The expression is often composed from these relational operators. == equals! = not equal < less than <= less than or equal > greater than >= greater than or equal R. Lindsay Todd () Beginning Programming for Engineers Beg 2 19 / 50

The if Statement Sample: oin Toss Program Relational Operators start hoose heads or tails Prompt human to call Get human s call coin = guess Program: cointoss.c # include <stdio.h> # include < stdlib.h> # include <time.h> int main () { int coin, guess ; srand ( time ( NULL )); No end Print message coin = rand () % 2; printf ("Your call (0: Heads, 1: Tails ): "); scanf (" %d", & guess ); if ( coin == guess ) { printf (" You called it correctly!\n"); return 0; R. Lindsay Todd () Beginning Programming for Engineers Beg 2 21 / 50

The if-else Statement The if Statement The if-else Statement Sometimes, need to separate actions depending on whether or not a condition is true. /* Previous... */ if (expression ) statement else estatement /* Following... */ This executes statement if expression is true; otherwise it executes estatement. It is common for statement and estatement to be compound statements (separate blocks). R. Lindsay Todd () Beginning Programming for Engineers Beg 2 23 / 50

The if Statement hained if-else Statements hained if-else Statements estatement can be another if statement. /* Previous... */ if (expression ) statement else if (expression ) statement. else estatement /* Following... */ R. Lindsay Todd () Beginning Programming for Engineers Beg 2 25 / 50

The if Statement hained if-else Statements Problem: High/Low Game We want a program to play High/Low. The program picks a number. The human player tries to guess it. The program indicates if the guess is too high, too low, or correct. Then it stops. Sample outputs: Results Guess my number (between 1 and 10): 5 Your guess was too small. The correct number was 6. Results Guess my number (between 1 and 10): 9 Your guess was too high. The correct number was 3. R. Lindsay Todd () Beginning Programming for Engineers Beg 2 27 / 50

The if Statement hained if-else Statements High/Low Algorithm start Pick a random number Ask player for guess 1 Pick a random number. 2 Ask the player for a guess. 3 Read in the guess. 4 ompare the guess, and print the correct message. 5 If the number was correct, stop. Read in guess Too low? No Too high? Yes Yes Print Low 6 Print our number. 7 Stop. No Print orrect Print High Print correct number end end R. Lindsay Todd () Beginning Programming for Engineers Beg 2 29 / 50

The if Statement hained if-else Statements Sample: High/Low Program: hilo.c /* Guess my number. */ # include <stdio.h> # include < stdlib.h> # include <time.h> int main () { int mynum, yournum ; srand ( time ( NULL )); /* Seed */ mynum = 1 + rand () % 10; /* Pick a number */ start Pick a random number Ask player for guess Read in guess Too low? Yes printf (" Guess my number ( between 1 and 10): "); scanf ("%d", & yournum ); if ( yournum < mynum ) { printf (" Your guess was too small.\n" ); else if ( yournum > mynum ) { printf (" Your guess was too high.\n"); else { printf (" You got it!\n" ); return 0; printf (" The correct number was %d.\n", mynum ); return 0; No Too high? No Print orrect end Yes Print High Print correct number end Print Low R. Lindsay Todd () Beginning Programming for Engineers Beg 2 31 / 50

The if Statement Logical Operators A need for logical operators Suppose we had some code: int a = 5, b = 4, c = 3; /* Some stuff */ if (a > b > c) { /* More stuff */ We probably want More stuff to be done. It won t! We evaluate a > b, which is 5 > 4, or 1. Then we evaluate 1 > c, which is 1 > 3, or 0. R. Lindsay Todd () Beginning Programming for Engineers Beg 2 33 / 50

Logical Operators The if Statement Logical Operators has logical operators. Negation!expression (negation) is 1 if expression is 0, and 0 otherwise.!0 1!1 0!2.0 0 if (! (a == 5)) { do stuff R. Lindsay Todd () Beginning Programming for Engineers Beg 2 35 / 50

The if Statement Logical Operators Logical Operators cont d Logical AND expression1 && expression2 is 1 if both expression1 and expression2 are true. If expression1 is 0, then expression2 is not even evaluated. 2 && 3 1 2 && 0 0 0 && 3 0 0 && 2/0 0 if (a!= 0 && b % a == 0) { do stuff R. Lindsay Todd () Beginning Programming for Engineers Beg 2 37 / 50

The if Statement Logical Operators Logical Operators cont d Logical OR expression1 expression2 is 1 if either expression1 or expression2 are true. If expression1 is true, then expression2 is not even evaluated. 2 3 1 0 3 1 2 0 1 0.0 0 0 if (a < 3 a > 10) { do stuff R. Lindsay Todd () Beginning Programming for Engineers Beg 2 39 / 50

The if Statement Logical Operators Problem: Smallest of 3 numbers We would like to read in three integers. Determine which one is the smallest, and display it. If the values are a, b, and c, there are four cases: a is smallest if a < b and a < c b is smallest if b < a and b < c c is smallest if c < a and c < b No smallest When? R. Lindsay Todd () Beginning Programming for Engineers Beg 2 40 / 50

The if Statement Flowchart: Smallest of 3 numbers Logical Operators start Ask for 3 integers Read in a, b, c a < b && a < c? Yes No b < a && b < c? Yes least = a No c < a && c < b? least = b No Print No smallest least = c Print least end end R. Lindsay Todd () Beginning Programming for Engineers Beg 2 41 / 50

The if Statement ode: Smallest of 3 numbers Logical Operators Program: small3.c /* Least of three numbers */ # include <stdio.h> start Ask for 3 integers int main () { int a, b, c, least ; printf (" Enter 3 integers : "); scanf ("%d, %d, %d", &a, &b, &c); if (a < b && a < c) { least = a; else if (b < a && b < c) { least = b; else if (c < b && c < a) { least = c; else { printf (" Oops! No smallest!\n"); return 0; printf (" Smallest is %d\n", least ); return 0; Read in a, b, c a < b && a < c? No b < a && b < c? No c < a && c < b? No Print No smallest end Yes Yes least = c least = b Print least end least = a R. Lindsay Todd () Beginning Programming for Engineers Beg 2 43 / 50

omputing the smallest The if Statement Logical Operators Program: small3.c /* Least of three numbers */ # include <stdio.h> int main () { int a, b, c, least ; printf (" Enter 3 integers : "); scanf ("%d, %d, %d", &a, &b, &c); if (a < b && a < c) { least = a; else if (b < a && b < c) { least = b; else if (c < b && c < a) { least = c; else { printf (" Oops! No smallest!\n"); return 0; printf (" Smallest is %d\n", least ); return 0; Results Enter 3 integers: 1,3,0 Smallest is 0 Results Enter 3 integers: 3,8,3 Oops! No smallest! R. Lindsay Todd () Beginning Programming for Engineers Beg 2 45 / 50

The while Statement Iteration with while Iteration is repeating the same statements in a program. Sometimes this is called looping. The while statement executes statement as long as expression is true. The expression is tested before statement is ever executed. while (expression ) statement R. Lindsay Todd () Beginning Programming for Engineers Beg 2 47 / 50

Problem: Powers of 2 The while Statement Powers of 2 Program We would like to generate and print the powers of two less than or equal to 1500. start We need a variable, i, to represent each power of two, starting with 2 0. If i is a power of 2, then 2i is the next power of 2. Repeatedly compute i, check if we are done, and printing i. i = 1 i <= 1500? No end Yes Print i i = i * 2 R. Lindsay Todd () Beginning Programming for Engineers Beg 2 48 / 50

No Yes Example: Powers of 2 The while Statement Powers of 2 Program Program: powerw.c /* Print powers of 2 <= 1500 */ # include <stdio.h> start i = 1 i <= 1500? end Print i i = i * 2 int main () { int i; i = 1; /* 2^0 */ while (i <= 1500) { printf ("%d\n", i); i = i * 2; return 0; 1 2 4 8 16 32 64 128 256 512 1024 R. Lindsay Todd () Beginning Programming for Engineers Beg 2 50 / 50