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

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

Week 2 C Fundamentals; Formatted Input/Output; int and float Types

Introducing C. Origins of C. Chapter 1. Standardization of C. Origins of C

Formatted Input/Output

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

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

Introduction to C Programming (Part A) Copyright 2008 W. W. Norton & Company. All rights Reserved

CMSC 246 Systems Programming

CMPUT 201: Practical Programming Methodology. Guohui Lin Department of Computing Science University of Alberta September 2018

Programming for Engineers C Preprocessor

Weeks 10/11 C Preprocessor Macros and Functions

Eastern Mediterranean University Department of Computer Engineering

The C Programming Language Part 2. (with material from Dr. Bin Ren, William & Mary Computer Science)

C: How to Program. Week /Mar/05

Lecture 3. More About C

Intermediate Programming, Spring 2017*

Lab Session # 1 Introduction to C Language. ALQUDS University Department of Computer Engineering

CPE 101, reusing/mod slides from a UW course (used by permission) Lecture 5: Input and Output (I/O)

CMPT 102 Introduction to Scientific Computer Programming. Input and Output. Your first program

Integer Representation. Variables. Real Representation. Integer Overflow/Underflow

1/31/2018. Overview. The C Programming Language Part 2. Basic I/O. Basic I/O. Basic I/O. Conversion Characters. Input/Output Structures and Arrays

Basic Types and Formatted I/O

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

CS Spring 2018 Homework #5

CSCI 2132 Software Development. Lecture 8: Introduction to C

Programming for Electrical and Computer Engineers. Loops

Chapter 7. Basic Types

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

CC112 Structured Programming

2. Numbers In, Numbers Out

Chapter 2 - Introduction to C Programming

!"#$% &'($) *+!$ 0!'" 0+'&"$.&0-2$ 10.+3&2),&/3+, %&&/3+, C,-"!.&/+"*0.&('1 :2 %*10% *%7)/ 30'&. 0% /4%./

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

Programming for Electrical and Computer Engineers. Pointers and Arrays

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

Spring 2018 NENG 202 Introduction to Computer Programming

Display Input and Output (I/O)

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

CpSc 1111 Lab 4 Formatting and Flow Control

Structured programming

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

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

Introduction to Computing Lecture 03: Basic input / output operations

2. Numbers In, Numbers Out

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

Computer System and programming in C

Programming for Engineers Introduction to C

Course Outline Introduction to C-Programming

Input/Output Week 5:Lesson 16.1

Basic Assignment and Arithmetic Operators

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

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

Structured programming. Exercises 3

Yacoub Sabatin Muntaser Abulafi Omar Qaraeen

Control Flow, Functions and Basic Linkage

Programming Language A

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

For questions 4 through 7, select the value assigned to the relevant variable, given the declarations: 3) ) This is not allowed

SEQUENTIAL STRUCTURE. Erkut ERDEM Hacettepe University October 2010

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

AN OVERVIEW OF C. CSE 130: Introduction to Programming in C Stony Brook University

2008/11/05: Lecture 15 CMSC 104, Section 0101 John Y. Park

Lecture 10: Recursive Functions. Computer System and programming in C 1

CpSc 1011 Lab 4 Formatting and Flow Control Windchill Temps

Introduction to the C Programming Language

printf("%c\n", character); printf("%s\n", "This is a string"); printf("%s\n", string); printf("%s\n",stringptr); return 0;

COSC121: Computer Systems: Runtime Stack

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

The C language. Introductory course #1

Midterm Exam. CSCI 2132: Software Development. March 4, Marks. Question 1 (10) Question 2 (10) Question 3 (10) Question 4 (10) Question 5 (5)

1.1 Introduction to C Language. Department of CSE

Full file at

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting

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

Special PRG Lecture No. 2. Professor David Brailsford Special PRG Lecture: Arrays

C Programming

Programming and Data Structures

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

Chapter 11 Introduction to Programming in C

Slides adopted from T. Ferguson Spring 2016

C-1. Overview. CSE 142 Computer Programming I. Review: Computer Organization. Review: Memory. Declaring Variables. Memory example

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

Chapter 1 & 2 Introduction to C Language

BSM540 Basics of C Language

Introduction to C. Systems Programming Concepts

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

printf( Please enter another number: ); scanf( %d, &num2);

Introduction to Programming

CSE123 LECTURE 3-1. Program Design and Control Structures Repetitions (Loops) 1-1

WARM UP LESSONS BARE BASICS

1/25/2018. ECE 220: Computer Systems & Programming. Write Output Using printf. Use Backslash to Include Special ASCII Characters

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

Should you know scanf and printf?

Q1: C input/output; operators / 46 Q2: Conditional statements / 34 Q3: While and do-while loops / 20 TOTAL SCORE / 100 Q4: EXTRA CREDIT / 10

Arithmetic type issues

Lecture 6. Statements

Yacoub Sabatin Muntaser Abulafi Omar Qaraeen. Introduction

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)

C-Programming. CSC209: Software Tools and Systems Programming. Paul Vrbik. University of Toronto Mississauga

Chapter 11 Introduction to Programming in C

Transcription:

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

Program: Printing a Pun pun.c The file name doesn t matter, but the.c extension is often required. for example: pun.c #include <stdio.h> int main(void) { printf("to C, or not to C: that is the question.\n"); return 0; } to compile % cc -o pun pun.c % gcc -o pun pun.c or to run %./pun 2

Program: Printing a Pun Revised pun.c printf doesn t automatically advance to the next output line when it finishes printing. #include <stdio.h> int main(void) { printf("to C"); printf(", or not to C:"); printf(" that i"); printf(" s the question. "); printf(" \n"); return 0; } 3

Program: Computing the Dimensional Weight of a Box use dweight.c Shipping companies often charge extra for boxes that are large but very light, basing the fee on volume instead of weight. The usual method to compute the dimensional weight is to divide the volume by 166 (the allowable number of cubic inches per pound). The dweight.c program computes the dimensional weight of a particular box: Dimensions: 12x10x8 Volume (cubic inches): 960 Dimensional weight (pounds): 6

Program: Computing the Dimensional Weight of a Box Division is represented by / in C, so the obvious way to compute the dimensional weight would be weight = volume / 166; In C, however, when one integer is divided by another, the answer is truncated : all digits after the decimal point are lost. The volume of a 12 10 8 box will be 960 cubic inches. Dividing by 166 gives 5 instead of 5.783. One solution is to add 165 to the volume before dividing by 166: weight = (volume + 165) / 166; A volume of 166 would give a weight of 331/166, or 1, while a volume of 167 would yield 332/166, or 2.

dweight.c /* Computes the dimensional weight of a 12" x 10" x 8" box */ #include <stdio.h> int main(void) { int height, length, width, volume, weight; height = 8; length = 12; width = 10; volume = height * length * width; weight = (volume + 165) / 166; printf("dimensions: %dx%dx%d\n", length, width, height); printf("volume (cubic inches): %d\n", volume); printf("dimensional weight (pounds): %d\n", weight); } return 0;

Program: Computing the Dimensional Weight of a Box (Revisited) dweight2.c is an improved version of the dimensional weight program in which the user enters the dimensions. Each call of scanf is immediately preceded by a call of printf that displays a prompt.

dweight2.c /* Computes the dimensional weight of a box from input provided by the user */ #include <stdio.h> int main(void) { int height, length, width, volume, weight; printf("enter height of box: "); scanf("%d", &height); printf("enter length of box: "); scanf("%d", &length); printf("enter width of box: "); scanf("%d", &width); volume = height * length * width; weight = (volume + 165) / 166; printf("volume (cubic inches): %d\n", volume); printf("dimensional weight (pounds): %d\n", weight); } return 0;

Program: Computing the Dimensional Weight of a Box (Revisited) Sample output of program: Enter height of box: 8 Enter length of box: 12 Enter width of box: 10 Volume (cubic inches): 960 Dimensional weight (pounds): 6 Note that a prompt shouldn t end with a new-line character.

Defining Names for Constants dweight.c and dweight2.c rely on the constant 166, whose meaning may not be clear to someone reading the program. Using a feature known as macro definition, we can name this constant: #define INCHES_PER_POUND 166 TODO: Change the code to use the macro definition

Program: Converting from Fahrenheit to Celsius The celsius.c program prompts the user to enter a Fahrenheit temperature; it then prints the equivalent Celsius temperature. Sample program output: Enter Fahrenheit temperature: 212 Celsius equivalent: 100.0 The program will allow temperatures that aren t integers. Defining SCALE_FACTOR to be (5.0f / 9.0f) instead of (5 / 9) is important. Note the use of %.1f to display celsius with just one digit after the decimal point.

celsius.c /* Converts a Fahrenheit temperature to Celsius */ #include <stdio.h> #define FREEZING_PT 32.0f #define SCALE_FACTOR (5.0f / 9.0f) int main(void) { float fahrenheit, celsius; printf("enter Fahrenheit temperature: "); scanf("%f", &fahrenheit); celsius = (fahrenheit - FREEZING_PT) * SCALE_FACTOR; printf("celsius equivalent: %.1f\n", celsius); } return 0;

Layout of a C Program (1/2) The amount of space between tokens usually isn t critical. At one extreme, tokens can be crammed together with no space between them, except where this would cause two tokens to merge: /* Converts a Fahrenheit temperature to Celsius */ #include <stdio.h> #define FREEZING_PT 32.0f #define SCALE_FACTOR (5.0f/9.0f) int main(void){float fahrenheit,celsius;printf( "Enter Fahrenheit temperature: ");scanf("%f", &fahrenheit); celsius=(fahrenheit-freezing_pt)*scale_factor; printf("celsius equivalent: %.1f\n", celsius);return 0;} adding spaces and blank lines to a program can make it easier to read and understand. 13

Layout of a C Program (2/2) Although extra spaces can be added between tokens, it s not possible to add space within a token without changing the meaning of the program or causing an error. fl oat fahrenheit, celsius; /*** WRONG ***/ fl oat fahrenheit, celsius; /*** WRONG ***/ Putting a space inside a string literal is allowed, although it changes the meaning of the string. Putting a new-line character in a string (splitting the string over two lines) is illegal: /*** WRONG ***/ printf("to C, or not to C: that is the question.\n"); 14

Program: Adding Fractions The addfrac.c program prompts the user to enter two fractions and then displays their sum. Sample program output: Enter first fraction: 5/6 Enter second fraction: 3/4 The sum is 38/24

Program: Adding Fractions /* Adds two fractions */ #include <stdio.h> int main(void) { int num1, denom1, num2, denom2, result_num, result_denom; printf("enter first fraction: "); scanf("%d/%d", &num1, &denom1); printf("enter second fraction: "); scanf("%d/%d", &num2, &denom2); result_num = num1 * denom2 + num2 *denom1; result_denom = denom1 * denom2; printf("the sum is %d/%d\n",result_num, result_denom) } return 0;

Program: Using printf to Format Numbers The tprintf.c program uses printf to display integers and floating-point numbers in various formats. /* Prints int and float values in various formats */ #include <stdio.h> int main(void) { int i; float x; i = 40; x = 839.21f; printf(" %d %5d %-5d %5.3d \n", i, i, i, i); printf(" %10.3f %10.3e %-10g \n", x, x, x); return 0; } 40 40 40 040 839.210 8.392e+02 839.21

Use printf to format the following string 2 digits for Major Number 2 digits for Minor Number 1 digit for cpu number 6 digit for sequence number nano second precision for timestamp 6 digit for process ID 1 character for command 1 character for I/O operation 10 characters for content 8,32 3 1 0.000000000 2208 Q R 0 + 2 [dd] 8,32 3 2 0.000002113 2208 G R 0 + 2 [dd]

How scanf Works (1/4) As it searches for a number, scanf ignores white-space characters space, horizontal and vertical tab, form-feed, and new-line A call of scanf that reads four numbers: scanf("%d%d%f%f", &i, &j, &x, &y); The numbers can be on one line or spread over several lines: 1-20.3-4.0e3 1-20.3-4.0e3 ssrsrrrsssrrssssrrrrrr (s = skipped; r = read) scanf peeks at the final new-line without reading it. 19

How scanf Works (2/4) #include <stdio.h> int main() { } int i, j; float x, y; scanf("%d%d%f%f", &i, &j, &x, &y); printf( i:%d\tj:%d\tx:%f\ty:%f\n, i, j, x, y); return; 1-20.3-4.0e3 1 2 1-20.3-4.0e3

How scanf Works (3/4) #include <stdio.h> int main() { } int i, j; scanf("%d/%d", &i, &j); printf( i:%d\tj:%d\n, i, j); return; 1 38/ 28 2 38 /28

How scanf Works (4/4) #include <stdio.h> int main() { } int i, j; scanf( %d/hello/%d", &i, &j); printf( i:%d\tj:%d\n, i, j); return; 1 38/ 28 2 38 /28 3 38 / 28 4 38/hel lo/ 28 5 38/hello/ 28