C Programming a Q & A Approach

Similar documents
ANSI C Programming Simple Programs

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

DEPARTMENT OF MATHS, MJ COLLEGE

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

C: How to Program. Week /Mar/05

A Fast Review of C Essentials Part I

Fundamentals of Programming

Chapter 2 - Introduction to C Programming

Fundamental of Programming (C)

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

Chapter 1 & 2 Introduction to C Language

Programming and Data Structures

Programming in C++ 5. Integral data types

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

ET156 Introduction to C Programming

Operators and Expressions:

UNIT- 3 Introduction to C++

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

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

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

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

Basics of Programming

Review of the C Programming Language for Principles of Operating Systems

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

Lecture 02 C FUNDAMENTALS

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

C Programming

Data Types and Variables in C language

Chapter 3: Operators, Expressions and Type Conversion

Visual C# Instructor s Manual Table of Contents

Data types, variables, constants

Programming for Engineers Introduction to C

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

Operators & Expressions

Review of the C Programming Language

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

Chapter 2: Overview of C. Problem Solving & Program Design in C

Unit 3. Operators. School of Science and Technology INTRODUCTION

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

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

Reserved Words and Identifiers

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

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

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

Full file at

BLM2031 Structured Programming. Zeyneb KURT

C Fundamentals & Formatted Input/Output. adopted from KNK C Programming : A Modern Approach

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

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++

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

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

Programming for Engineers: Operators, Expressions, and Statem

DECLARATIONS. Character Set, Keywords, Identifiers, Constants, Variables. Designed by Parul Khurana, LIECA.


C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

Programming Fundamentals (CS 302 ) Dr. Ihsan Ullah. Lecturer Department of Computer Science & IT University of Balochistan

Department of Computer Applications

Fundamentals of C. Structure of a C Program

Objectives. In this chapter, you will:

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

Chapter 2: Using Data

SEQUENTIAL STRUCTURE. Erkut ERDEM Hacettepe University October 2010

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

A Java program contains at least one class definition.

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

CS102: Variables and Expressions

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Computer System and programming in C

Lecture 3. More About C

Variables in C. Variables in C. What Are Variables in C? CMSC 104, Fall 2012 John Y. Park

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS

INTRODUCTION 1 AND REVIEW

Introduction to C# Applications

Declaration and Memory

UNIT 3 OPERATORS. [Marks- 12]

VARIABLES AND CONSTANTS

.. Cal Poly CPE 101: Fundamentals of Computer Science I Alexander Dekhtyar..

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur

CSCI 171 Chapter Outlines

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

Operators. Java operators are classified into three categories:

3. Java - Language Constructs I

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

>B<82. 2Soft ware. C Language manual. Copyright COSMIC Software 1999, 2001 All rights reserved.

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

XC Specification. 1 Lexical Conventions. 1.1 Tokens. The specification given in this document describes version 1.0 of XC.

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

C-LANGUAGE CURRICULAM

C Language, Token, Keywords, Constant, variable

Chapter 2. Outline. Simple C++ Programs

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

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

Fundamentals of Programming Session 4

Programming. C++ Basics

Programming in C++ 6. Floating point data types

The C++ Language. Arizona State University 1

Structures, Operators

Transcription:

C Programming a Q & A Approach by H.H. Tan, T.B. D Orazio, S.H. Or & Marian M.Y. Choy Chapter 2 Variables, Arithmetic Expressions and Input/Output

2.1 Variables: Naming, Declaring, Assigning and Printing Values To calculate the area of 10,000 triangles. Given lengths of three sides three angles Need to make up your own variable names, e.g. lengths: a, b, c angles: a, b, g For programming in C, the situation is similar choose the variable names, consist of entire words rather than single characters easier to understand your programs if given very descriptive names to each variable 2

2.1 Variables: Naming, Declaring, Assigning and Printing Values We may use variable names Lengths: length1, length2, length3 Angles: angle1, angle2, angle3 Much less ambiguous than their algebraic counterparts Expressions look more cumbersome length of expression may span over 1 line Disadvantage which we simply must live with Try your best to make the name descriptive having mnemonic significance 3

2.1 Variables: Naming, Declaring, Assigning and Printing Values int month; float expense, income; month = 12; expense = 111.1; income = 100.; printf ("Month=%2d, Expense=$%9.2f\n", month, expense); month = 11; expense = 82.1; printf ("For the %2dth month of the year\n" "the expenses were $%5.2f \n" "and the income was $%6.2f\n\n", month, expense, income); 4

2.1 Variables: Naming, Declaring, Assigning and Printing Values int month; float expense, income; month = 12; expense = 111.1; income = 100.; printf ("Month=%2d, Expense=$%9.2f\n", month, expense); month = 11; expense = 82.1; printf ("For the %2dth month of the year\n" "the expenses were $%5.2f \n" "and the income was $%6.2f\n\n", month, expense, income); 5

Concepts Variable names must be declared before used Declare all your variable names near the beginning of your program Variable names are classified as identifiers first character must be non-digit characters a z, A Z, or _ other characters must be non-digit characters a z, A Z, _, or digit 0 9 Valid examples apple1 interest_rate xfloat Income one_two Invalid 1apple interest_rate% float In come one.two 6

Table 2.1 Some Constraints on Identifiers Topic Maximum number of characters in an internal identifier (i.e., identifier within a function) Use of C reserved words, also called keywords, as identifier Use of blank within an identifier Comment ANSI C allows a maximum number of 31 characters for names of internal identifiers Not allowed; i.e., do not use these words: auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while Not allowed, because an identifier is a token 7

Table 2.1 Some Constraints on Identifiers Topic Use of standard identifiers such as printf Use of uppercase or mixed-case Comment Standard identifiers, such as the function name printf, can be used as variable names. However, their use is not recommended because it leads to confusion. Allowed; however, many programmers use lowercase characters for variable names and uppercase for constant names. Differentiate your identifiers by using different characters rather than different cases 8

Keyword Identifier type token for which C has a defined purpose Cannot use them as variable names Number of keywords in C is very small, just 32 Refer to Table 2.1 9

Assignment Statement General form variable_name = value; Assigns a value to a variable Causes a value to be stored in the variable s memory location Equal sign(=) does not really mean equal 10

printf To display the value of a variable or constant on the screen printf(format_string,argument_list); format_string plain characters displayed directly unchanged on the screen, e.g. This is C conversion specification(s) used to convert, format and display argument(s) from the argument_list escape sequences control the cursor, for example, the newline \n Each argument must have a format specification. For example, printf("month=%5d \n",month); 11

Further Exploration Effect of declaring variables causes the C compiler to know reserve space in memory for storing values of variables ANSI C requires int be capable of handling a minimum range of -32767 to 32767. This requires 16 bits (2 bytes) of memory Most modern compiler used 4 bytes for int float type value typically occupies 4 bytes, i.e., 32 bits The bit pattern for 32 stored as an int is completely different from the bit pattern for storing 32. as a float. We should treat int and float as different things although they belong to numeric values! 12

Arithmetic Operators and Expressions Consists of a sequence of operand(s) and operator(s) that specify the computation of a value Look much like algebraic expressions that you write d = x/y; // x divided by y Assigns the value of the arithmetic expression(division) on the right to the variable on the left 13

Output 14

Example 1 int i,j,k,p,m,n; float a,b,c,d,e,f,g,h,x,y; i=5; j=5; k=11; p=3; x=3.0; y=4.0; printf("... Initial values...\n"); printf("i=%4d, j=%4d\nk=%4d, p=%4d\nx=%4.2f, y=%4.2f\n\n", i,j,k,p,x,y); 15

Example 1 a=x+y; b=x-y; c=x*y; d=x/y; e=d+3.0; f=d+3; i=i+1; j=j+1; printf("... Section 1 output...\n"); printf("a=%5.2f, b=%5.2f\nc=%5.2f, d=%5.2f\n" "e=%5.2f, f=%5.2f\ni=%5d, j=%5d \n\n", a,b, c,d, e,f, i,j); 16

Example 1 m=k%p; n=p%k; i++; ++j; e--; --f; printf("... Section 2 output...\n"); printf("m=%4d, n=%4d\ni=%4d, j=%4d\n" "e=%4.2f, f=%4.2f\n",m,n, i,j, e,f); 17

Arithmetic Operators and Expressions Operators ++, --, and % ++ increment operator, can be placed before or after a variable increase the value of the variable by 1 i++; or ++i; equivalent to i=i+1; i--; or --i; same as i=i-1; Only difference between i++ and ++i is in order of increment (addressed later) % is a remainder operator must be placed between two integer variables or constants e.g. 11%3 return 2 18

Arithmetic Operators and Expressions Cannot write x/y = d; i + 1 = i; Left side of assignment statement can have only single variable Single variables are allowed to be lvalues (allowed to be on the left side of assignment ) Expressions are rvalues (allowed on the right side of assignment ) 19

Reading Data from The Keyboard We can instruct the computer to retrieve data from various input devices the keyboard a mouse the hard disk drive Programs that have input from the keyboard usually create a dialogue between the program and the user during execution 20

Reading Data from The Keyboard float income; double expense; int month, hour, minute; printf ("What month is it?\n"); scanf ("%d", &month); printf ("You have entered month=%5d\n",month); 21

Reading Data from The Keyboard printf ("Please enter your income and expenses\n"); scanf ("%f %lf",&income,&expense); printf ("Entered income=%8.2f, expenses=%8.2lf\n", income,expense); printf ("Please enter the time, e.g.,12:45\n"); scanf ("%d : %d",&hour,&minute); printf ("Entered Time = %2d:%2d\n",hour,minute); 22

Reading Data from The Keyboard In order for the user to know what should be done, input prompt to create a dialog is used Output dialogue 23

Reading Data from The Keyboard scanf() function scanf (format_string, argument_list); format_string converts characters in the input into values of a specific type argument_list contains the address of the variable(s) into which the input data are stored. e.g. scanf("%f%lf",&income,&expense); 1 st keyboard input data converted to float (%f) => income 2 nd keyboard input converted to double (%lf) => expense 24

Reading Data from The Keyboard scanf() function scanf("%f%lf", &income, &expense); &income stands for the address of the memory cell for income & : address of operator &income - pass the address of variable income to function scanf By giving scanf the address, the program knows where in memory to put the value typed 25

Reading Data from The Keyboard double: C s floating-point (real) data types Occupies twice the memory (8 bytes) of the float type (4 bytes) Provide extra precision increase the range and the number of significant digits Computation time increase accordingly, thus you may choose float in case of efficiency concern, i.e. float income; 26

More on Formatting Using the define directive to define constants More about conversion specifications and their components Scientific notation Flags in conversion specifiers 27

Preprocessor To create a constant macro use a preprocessor directive begin with the symbol # (which must begin the line) semicolon must not be used at the end General form #define symbolic_name replacement #define DAYS_IN_YEAR 365 Draw equivalent of DAYS_IN_YEAR to 365 Prior to translation into machine code, the preprocessor replaces every symbolic_name in the program with the given replacement printf("days in year=%5d\n",days_in_year); after preprocessing becomes printf("days in year=%5d\n",365); 28

Conversion Specification Complete structure of format specifications is %[flag][field width][.precision]type [ ] are optional 29

Flags and Types in ANSI C Component flag = - flag = + flag = 0 field width Use This flag causes the output to be left justified within the given field width This flag causes the output to be right justified within the given field width and a plus sign displayed if the result is positive This flag causes leading zeros to be added to reach the minimum field width; the flag is ignored if the 2 flag is used simultaneously This integer represents the minimum number of character spaces reserved to display the entire output (including the decimal point, digits before and after the decimal point, and the sign). If the specified field width is not given or is less than the actual field width, the field width is automatically expanded on print out to accommodate the value being displayed. The field width and precision are used together to determine how many digits before and after a decimal point will be displayed precision type = d type = f For floating data types, precision specifies the number of digits after the decimal point to be displayed. The default precision for float type (e, E, or f) data is six. Precision also can be used for integer type data, where it specifies the minimum number of digits to be displayed. If the data to be displayed has fewer digits than the specified precision, the C compiler adds leading zero(s) on the left of the output For int type data The output is converted to decimal notation in the form of [sign]ddd.dddd, where the number of digits after the decimal point is equal to the specified precision type = e or E The output is converted to scientific notation in the form of [sign]d.dddd e[sign]ddd, where the number of digits before the decimal point is one, the number of digits after the decimal point is equal to the specified precision, and the number of exponent digits is at least two. If the value is zero, the exponent is 0. 30

Conversion Specification If the precision specified for a real is less than actual, displays only the number of digits in the specified precision (trailing digits are not lost from memory, they simply are not displayed) greater than actual, adds trailing zeros to make the displayed precision equal to the precision specified not specified, makes the precision equal to six The flag left-justifies a value that is put in a field width that is greater than the actual. 31

float income = 1234567890.12; printf ("CONVERSION SPECIFICATIONS FOR INTEGERS \n\n"); printf ("Days in year = \n" "[[%1d]] \t(field width less than actual)\n" "[[%9d]] \t(field width greater than actual)\n" "[[%d]] \t(no field width specified) \n\n\n", DAYS_IN_YEAR, DAYS_IN_YEAR, DAYS_IN_YEAR); 32

printf ("CONVERSION SPECIFICATIONS FOR REAL NUMBERS\n\n"); printf ("Cases for precision being specified correctly \n"); printf ("PI = \n" "[[%1.5f]] \t\t(field width less than actual) \n" "[[%15.5f]] \t(field width greater than actual)\n" "[[%.5f]] \t\t(no field width specified) \n\n", PI,PI,PI); 33

printf ("Cases for field width being specified correctly \n"); printf ("PI = \n" "[[%7.2f]] \t\t(precision less than actual) \n" "[[%7.8f]] \t\t(precision greater than actual)\n" "[[%7.f]] \t\t(no precision specified) \n\n", PI,PI,PI); 34

Examples 35

Conversion Specification Display int with %f or float with %d? likely get nonsensical values or zeros displayed common error beginners make Why was so much attention given to the printf statement? will write printf statements very frequently can substantially reduce your programming errors 36

Field Display Conversion Flag width Type Precision Note ( means blank) %+5d + 5 d none +365 Right-justified output, 1 sign added, total characters displayed is five %-5d - 5 d none 365 Flag is 2, so output is left justified %1d none 1 d none 365 Specified field width is less than the actual width, all characters in the value are displayed, no truncation occurs %0.5d zero 0 d 5 00365 Flag is 0, so output is prefixed with zeros, precision is 5, so the number of characters to be printed is five %d none none d none 365 Field width is undefined, all characters in the value are displayed, no truncation occurs; no blanks are added; value is left justified %+9.5f + 9 f 5 +3.14160 Total digits, including blanks, is nine %-9.5f - 9 f 5 3.14160 Flag is -, left-adjusted output %1.3f none 1 f 3 3.142 Uses precision 3, note the result is 3.142, not 3.141 %f none none f none 3.141600 Uses the default precision, 6 %+12.4e 1 15 e 4 1.2346e+009 output, total digits is 12, field width of 15 accommodates the e and 1, precision is 4 %-12.4e 2 15 e 4 1.2346e+009 Same as previously, but flag -, so output is left justified %5.2e none 5 e 2 1.23e+009 Precision is 2; field width is too short, so C uses minimum field width for output %E none none E none 1.234568E1009 C uses default precision of 6; field width is too short, so C uses minimum field width for output 37

Mixed Type Arithmetic, Compound Assignment Giving variables their first numerical values is called initialising them, e.g. x = 5; Usually complicated expression is placed on RHS Order of performance of numerical operations can be controlled Rules about the order of operation of +, -, *, / are established by setting the precedence of the operators Operators of higher precedence are executed first while those of lower precedence are executed later 38

Variable Initialisation/Increment Operator How do we initialise variables? 1. Uses an assignment statement, e.g. e=3; 2. Initialises in a declaration statement, e.g. float a=7, b=6; int i = 1, j =1; k = i++; h = ++j? For 1 st expression, 1. value of i is first assigned to k 2. i is then incremented (post-increment ++) from 1 to 2 For 2 nd one, 1. value of j is first incremented (pre-increment operator ++) from 1 to 2. 2. Then the new j value, now equal to 2, is assigned to h 39

Mixed Data Type Calculation 6.0/4.0 => 1.5 6/4 => 1 6/4.0 => 1.5 C converts integer to real temporarily and perform the operation 40

cast Operators Change the type of an expression temporarily General form (type) expression Force a floating Point division int aa=5, bb=2; float xx; xx = (float) aa / bb; xx = 2.5, otherwise xx = 2.0 41

Operator Name No of operands Position Associativity Precedence ( parentheses unary prefix L to R 1 ) parentheses unary postfix L to R 1 + positive sign unary prefix R to L 2 - negative sign unary prefix R to L 2 ++ post-increment unary postfix L to R 2 -- post-decrement unary postfix L to R 2 ++ pre-increment unary prefix R to L 2 -- pre-decrement unary prefix R to L 2 += addition and assignment binary infix R to L 2 -= subtraction and assignment *= multiplication and assignment binary infix R to L 2 binary infix R to L 2 /= division and assignment binary infix R to L 2 %= remainder and assignment binary infix R to L 2 % remainder binary infix L to R 3 * multiplication binary infix L to R 3 / division binary infix L to R 3 + addition binary infix L to R 4 - subtraction binary infix L to R 4 = assignment binary infix R to L 5 42

Controlling Precedence Arithmetic operators located within the parentheses() always have highest precedence Example z = ((a+b)*c/d); a+b evaluated first 43

Associativity Specifies the direction of evaluation of the operators with the same precedence First evaluated 1+2-3 Next evaluated Direction of evaluation 44

Side Effect Primary effect of evaluating an expression is arriving at a value for that expression Anything else occurs during evaluation of expression is considered a side effect eg. Assume i=7, j = i++; j=7 is primary effect i is changed to 8, is side effect eg. j = (i=4) + (k=3) (m=2); j = 5 is primary effect (4 + 3 2) Three side effects 1. Set i equal to 4 2. Set k equal to 3 3. Set m equal to 2 45

Further Exploration Assign an integer value to a float variable convert the result to float and store to variable e.g., p = 6 / 4; floating variable p will store 1.0 Result of the expression ( 6/5)? ANSI C standard specifies the result is implementation defined. compiler has a choice of rounding up or down give either 1 or 2 46

Dangers of Side Effects Can be confusing, for example, k = (k=4) * (j=3); k will be 12 instead of 4 Best not to use side effects except in their simplest form 47

Summary #define symbolic_name replacement where symbolic_name occurred throughout the rest of program will be replaced by replacement during compilation by preprocessor Format specifications %[flag][field width][.precision]type where format string components enclosed by [ ] are optional Output of a float number to scientific notation is [sign]d.ddd e[sign]ddd where d represents a digit 48

Summary During mixed mode (different data types) arithmetic, C will automatically convert one of the operands to facilitate calculations Sometimes type casting can be used to explicitly change data type during calculation (type) operand where type is the target type being converted into operand is the data to be casted 49