C Programming

Similar documents
CSc 10200! Introduction to Computing. Lecture 4-5 Edgardo Molina Fall 2013 City College of New York

Lecture 4 Tao Wang 1

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

Basics of Programming

Reserved Words and Identifiers

Chapter 3 Structure of a C Program

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.

Unit 3. Operators. School of Science and Technology INTRODUCTION

ANSI C Programming Simple Programs

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

UNIT- 3 Introduction to C++

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

Operators and Expressions:

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Visual C# Instructor s Manual Table of Contents

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

Fundamental of Programming (C)

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Lecture 3 Tao Wang 1

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Week 3 More Formatted Input/Output; Arithmetic and Assignment Operators

Full file at

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants

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

Chapter 2: Using Data

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

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

C: How to Program. Week /Mar/05

CHAPTER 3 Expressions, Functions, Output

Types and Expressions. Chapter 3

The C++ Language. Arizona State University 1

Lecture 3. More About C

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.

Programming in C++ 5. Integral data types

Chapter 2 - Introduction to C Programming

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

Data types, variables, constants

Fundamentals of Programming Session 7

Computers Programming Course 5. Iulian Năstac

3. Java - Language Constructs I

UNIT 3 OPERATORS. [Marks- 12]

Structured Programming. Dr. Mohamed Khedr Lecture 4

C Programming a Q & A Approach

Overview (4) CPE 101 mod/reusing slides from a UW course. Assignment Statement: Review. Why Study Expressions? D-1

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

Chapter 2. Lexical Elements & Operators

Data Types and Variables in C language

Course Outline Introduction to C-Programming

Programming for Engineers Introduction to C

Fundamentals of Programming Session 4

CMSC 104 -Lecture 6 John Y. Park, adapted by C Grasso

C++ Programming: From Problem Analysis to Program Design, Third Edition

2. Numbers In, Numbers Out

Programming Fundamentals. With C++ Variable Declaration, Evaluation and Assignment 1

Fundamentals of Programming

A Fast Review of C Essentials Part I

Number Systems, Scalar Types, and Input and Output

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

4. Inputting data or messages to a function is called passing data to the function.

Chapter 4: Basic C Operators

WARM UP LESSONS BARE BASICS

Computer System and programming in C

Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language. Dr. Amal Khalifa. Lecture Contents:

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Chapter 2: Using Data

CS110: PROGRAMMING LANGUAGE I

Operators & Expressions

Fundamental of C programming. - Ompal Singh

Objectives. In this chapter, you will:

Fundamentals of Programming. Lecture 3: Introduction to C Programming

Chapter 3. Numeric Types, Expressions, and Output

Structured programming. Exercises 3

COP 3275: Chapter 04. Jonathan C.L. Liu, Ph.D. CISE Department University of Florida, USA

THE FUNDAMENTAL DATA TYPES

2. Numbers In, Numbers Out

Engineering Problem Solving with C++, Etter/Ingber

Chapter 1 & 2 Introduction to C Language

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

Full file at

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

Operators in C. Staff Incharge: S.Sasirekha

Guide for The C Programming Language Chapter 1. Q1. Explain the structure of a C program Answer: Structure of the C program is shown below:

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

C Programming for Electronic Engineers

Outline. Data and Operations. Data Types. Integral Types

CSCI 2132: Software Development. Norbert Zeh. Faculty of Computer Science Dalhousie University. Introduction to C. Winter 2019

3. Types of Algorithmic and Program Instructions

Basic Assignment and Arithmetic Operators

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

Full file at C How to Program, 6/e Multiple Choice Test Bank

1.3b Type Conversion

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

Programming for Engineers Iteration

Work relative to other classes

Chapter 3 : Assignment and Interactive Input (pp )

The cin Object. cout << "Enter the length and the width of the rectangle? "; cin >> length >> width;

Transcription:

204216 -- C Programming Chapter 3 Processing and Interactive Input Adapted/Assembled for 204216 by Areerat Trongratsameethong A First Book of ANSI C, Fourth Edition

Objectives Assignment Mathematical Library Functions Interactive Input Formatted Output Symbolic Constants Case Study: Interactive Input Common Programming and Compiler Errors A First Book of ANSI C, Fourth Edition 2

Assignment The general syntax for an assignment statement is variable = operand; The operand to the right of the assignment operator (=) can be a constant, a variable, or an expression The equal sign in C does not have the same meaning as an equal sign in algebra length = 25; is read length is assigned the value 25 or length 25 Subsequent assignment statements can be used to change the value assigned to a variable length = 3.7; length = 6.28; // เราสามารถก าหนดค าข อม ลใหม ให ก บต วแปรได A First Book of ANSI C, Fourth Edition 3

Assignment (2) The operand to the right of the equal sign in an assignment statement can be a variable or any valid C expression sum = 3 + 7; product =.05 * 14.6; The value of the expression to the right of = is computed first and then the calculated value is stored in the variable to the left of = Variables used in the expression to the right of the = must be initialized if the result is to make sense amount + 1892 = 1000 + 10 * 5 is invalid! A First Book of ANSI C, Fourth Edition 4

Assignment (3) If width and length were not initialized, the computer uses the value that happens to occupy that memory space previously (compiler would probably issue a warning) A First Book of ANSI C, Fourth Edition 5

Assignment (4) = has the lowest precedence of all the binary and unary arithmetic operators introduced in Section 2.4 (See slide No. 38 of Chapter 2) Multiple assignments are possible in the same statement a = b = c = 25; All = operators have the same precedence Operator has right-to-left associativity c = 25;// step 1 b = c; // step 2 a = b; // step 3 A First Book of ANSI C, Fourth Edition 6

Implicit Type Conversions Data type conversions take place across assignment operators double result; result = 4; //integer 4 is converted to 4.0 The automatic conversion across an assignment operator is called an implicit type conversion int answer; answer = 2.764; //2.764 is converted to 2 Here the implicit conversion is from a higher precision to a lower precision data type; the compiler will issue a warning A First Book of ANSI C, Fourth Edition 7

Explicit Type Conversions (Casts) The operator used to force the conversion of a value to another type is the cast operator (datatype) expression where datatype is the desired data type of the expression following the cast Example: double sum; (int) sum; If sum is declared as double sum;, (int) sum is the integer value determined by truncating sum s fractional part A First Book of ANSI C, Fourth Edition 8

Assignment Variations Two major steps for: sum = sum + 10; Step 1: Step 2: A First Book of ANSI C, Fourth Edition 9

Assignment Variations (2) Assignment expressions like sum = sum + 25 can be written using the following operators: += -= *= /= %= Example: sum = sum + 10; // is equivalent to below statement sum += 10; price = price * rate // is equivalent to below statement price *= rate price *= rate + 1 // is equivalent to below statement price = price * (rate + 1) A First Book of ANSI C, Fourth Edition 10

Accumulating The first statement initializes sum to 0 This removes any previously stored value in sum that would invalidate the final total A previously stored number, if it has not been initialized to a specific and known value, is frequently called a garbage value A First Book of ANSI C, Fourth Edition 11

Accumulating (2) A First Book of ANSI C, Fourth Edition 12

Counting A counting statement is very similar to the accumulating statement variable = variable + fixednumber; Examples: i = i + 1; m = m + 2; Increment operator (++): variable = variable + 1; can be replaced by variable++; //or ++variable; A First Book of ANSI C, Fourth Edition 13

Counting (2) A First Book of ANSI C, Fourth Edition 14

Counting (3) When the ++ operator appears before a variable, it is called a prefix increment operator; when it appears after a variable, it is called postfix increment operator k = ++n; // is equivalent to two steps shown below n = n + 1; // increment n first (step 1) k = n; // assign n's value to k (step 2) k = n++; // is equivalent to two steps shown below k = n; // assign n's value to k (step 1) n = n + 1; // and then increment n (step 2) A First Book of ANSI C, Fourth Edition 15

Counting (4) Prefix decrement operator: the expression k = --n; first decrements the value of n by 1 before assigning the value of n to k n = n - 1; // decrement n first (step 1) k = n; // assign n's value to k (step 2) Postfix decrement operator: the expression k = n--; first assigns the current value of n to k and then reduces the value of n by 1 k = n; // assign n's value to k (step 1) n = n - 1; // and then decrement n (step 2) A First Book of ANSI C, Fourth Edition 16

Mathematical Library Functions A First Book of ANSI C, Fourth Edition 17

Mathematical Library Functions (2) The argument to sqrt must be floating-point value; passing an integer value results in a compiler error Return value is double-precision Must include #include <math.h> A First Book of ANSI C, Fourth Edition 18

Mathematical Library Functions (3) Argument need not be a single constant A First Book of ANSI C, Fourth Edition 19

Mathematical Library Functions (4) The step-by-step evaluation of the expression 3.0 * sqrt(5 * 33-13.91) / 5; A First Book of ANSI C, Fourth Edition 20

Mathematical Library Functions (5) Determine the time it takes a ball to hit the ground after it has been dropped from an 800-foot tower time = sqrt(2 * distance/g), where g = 32.2 ft/sec2 A First Book of ANSI C, Fourth Edition 21

Interactive Input This program must be rewritten to multiply different numbers scanf() is used to enter data into a program while it is executing; the value is stored in a variable It requires a control string as the first argument inside the function name parentheses A First Book of ANSI C, Fourth Edition 22

Interactive Input (2) The control string passed to scanf() typically consists of conversion control sequences only scanf() requires that a list of variable addresses follow the control string scanf("%d", &num1); A First Book of ANSI C, Fourth Edition 23

Interactive Input (3) This statement produces a prompt Address operator (&) A First Book of ANSI C, Fourth Edition 24

Interactive Input (4) scanf() can be used to enter many values scanf("%f %f",&num1,&num2); //"%f%f" is the same A space can affect what the value being entered is when scanf() is expecting a character data type scanf("%c%c%c",&ch1,&ch2,&ch3); stores the next three characters typed in the variables ch1, ch2, and ch3; if you type x y z, then: x is stored in ch1, a blank is stored in ch2, and y is stored in ch3 scanf("%c %c %c",&ch1,&ch2,&ch3); causes scanf() to look for three characters, each character separated by exactly one space A First Book of ANSI C, Fourth Edition 25

Interactive Input (5) In printing a double-precision number using printf(), the conversion control sequence for a single-precision variable, %f, can be used When using scanf(), if a double-precision number is to be entered, you must use the %lf conversion control sequence scanf() does not test the data type of the values being entered In scanf("%d %f", &num1, &num2), if user enters 22.87 22 is stored in num1 and.87 is stored in num2 A First Book of ANSI C, Fourth Edition 26

Caution: The Phantom Newline Character Output Type in a character: m The keystroke just accepted is 109 Type in another character: The keystroke just accepted is 10 10 is Enter Key (New Line) (in keyboard buffer) A First Book of ANSI C, Fourth Edition 27

Caution: The Phantom Newline Character (2) A First Book of ANSI C, Fourth Edition 28

Caution: The Phantom Newline Character (3) A First Book of ANSI C, Fourth Edition 29

A First Look at User-Input Validation A First Book of ANSI C, Fourth Edition 30

A First Look at User-Input Validation (2) As written, Program 3.12 is not robust The problem becomes evident when a user enters a non-integer value Enter three integer numbers: 10 20.68 20 The average of 10, 20, and -858993460 is -286331143.333333 Handling invalid data input is called user-input validation Validating the entered data either during or immediately after the data have been entered Providing the user with a way of reentering any invalid data A First Book of ANSI C, Fourth Edition 31

Formatted Output Output is not aligned 6 18 124 --- 148 6 18 124 --- 148 Field Width Specifier A First Book of ANSI C, Fourth Edition 32

Formatted Output (2) A First Book of ANSI C, Fourth Edition 33

Format Modifiers Left justification: produces the display 59۸۸۸۸۸۸۸۸ Explicit sign display: produces the display ۸۸۸۸۸۸۸+59 Format modifiers may be combined printf("%-10d",59); printf("%+10d",59); %-+10d would cause an integer number to both: display its sign and be left-justified in a field width of 10 spaces The order of the format modifiers is not critical %+-10d is the same A First Book of ANSI C, Fourth Edition 34

Other Number Bases [Optional] The decimal (base 10) value of 15 is 15. The octal (base 8) value of 15 is 17. The hexadecimal (base 16) value of 15 is f. A First Book of ANSI C, Fourth Edition 35

Other Number Bases (2) A First Book of ANSI C, Fourth Edition 36

Other Number Bases (3) The decimal value of the letter a is 97. The octal value of the letter a is 141. The hex value of the letter a is 61. A First Book of ANSI C, Fourth Edition 37

Other Number Bases (4) A First Book of ANSI C, Fourth Edition 38

Symbolic Constants Literal data refers to any data within a program that explicitly identifies itself Literal values that appear many times in the same program are called magic numbers C allows you to define the value once by equating the number to a symbolic name #define SALESTAX 0.05 #define PI 3.1416 Also called symbolic constants and named constants A First Book of ANSI C, Fourth Edition 39

Symbolic Constants (2) # sign is a signal to a C preprocessor A First Book of ANSI C, Fourth Edition 40

Case Study: Interactive Input A First Book of ANSI C, Fourth Edition 41

Common Programming Errors Forgetting to assign initial values to all variables before the variables are used in an expression Calling sqrt() with an integer argument Forgetting to use the address operator, &, in front of variable names in a scanf() function call Not including the correct control sequences in scanf() function calls for the data values that must be entered Including a message within the control string passed to scanf() A First Book of ANSI C, Fourth Edition 42

Common Programming Errors (2) Terminating a #define command to the preprocessor with a semicolon Placing an equal sign in a #define command when equating a symbolic constant to a value Using the increment and decrement operators with variables that appear more than once in the same expression Being unwilling to test a program in depth A First Book of ANSI C, Fourth Edition 43

Common Compiler Errors A First Book of ANSI C, Fourth Edition 44

Common Compiler Errors (2) A First Book of ANSI C, Fourth Edition 45

Summary Arithmetic calculations can be performed using assignment statements or mathematical functions The assignment symbol, =, is an operator C provides the +=, -=, *= and /= assignment operators The increment operator, ++, adds 1 to a variable The decrement operator, --, subtracts 1 from a variable C provides library functions for calculating square root, logarithmic, and other mathematical computations A First Book of ANSI C, Fourth Edition 46

Summary (2) Mathematical functions may be included within larger expressions scanf() is a standard library function used for data input When a scanf() function is encountered, the program temporarily suspends further statement execution until sufficient data has been entered for the number of variable addresses contained in the scanf() function call A First Book of ANSI C, Fourth Edition 47

Summary (3) It is good programming practice to display a message, prior to a scanf() function call, that alerts the user as to the type and number of data items to be entered Field width specifiers can be included with conversion control sequences to explicitly specify the format of displayed fields Each compiled C program is automatically passed through a preprocessor Expressions can be made equivalent to a single identifier using the preprocessor #define command A First Book of ANSI C, Fourth Edition 48