Numeric Data Types in C

Similar documents
Number Systems, Scalar Types, and Input and Output

Programming Language A

The New C Standard (Excerpted material)

Programming. Elementary Concepts

CS107, Lecture 3 Bits and Bytes; Bitwise Operators

CS107, Lecture 2 Bits and Bytes; Integer Representations

Types, Variables, and Constants

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

CS 107 Lecture 3: Integer Representations

Data Type Fall 2014 Jinkyu Jeong

Expressions. Eric McCreath

Simple Data Types in C. Alan L. Cox

Representing and Manipulating Integers. Jo, Heeseung

Arithmetic Operators. Portability: Printing Numbers

Representing Integers. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

Introduction to C Language

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

Computers Programming Course 5. Iulian Năstac

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

Representing and Manipulating Integers Part I

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

Computer System and programming in C

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

Internal representation. Bitwise operators

Internal representation. Bitwise operators

Operators and Expressions:

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

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

Lecture 03 Bits, Bytes and Data Types

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

Multiple Choice Questions ( 1 mark)

Operators and Expression. Dr Muhamad Zaini Yunos JKBR, FKMP

CS3157: Advanced Programming. Outline

Functions. Systems Programming Concepts

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

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

CS2141 Software Development using C/C++ C++ Basics

COMP327 Mobile Computing Session: Tutorial 2 - Operators and Control Flow

(T) x. Casts. A cast converts the value held in variable x to type T

Internal representation. Bitwise operators

ESC101N Fundamentals of Computing

Types, Operators and Expressions

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Representing Integers

Basics of Programming

in normal arithmetic = == = == 5 7 x 2 = 24 7 * 2 == = 3 remainder 1 7 / 2 7 % 2

Integers. Today. Next time. ! Numeric Encodings! Programming Implications! Basic operations. ! Floats

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

공학프로그래밍언어 (PROGRAMMING LANGUAGE FOR ENGINEERS) -VARIABLE AND DATA TYPES- SPRING 2015, SEON-JU AHN, CNU EE

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

Data Types and Variables in C language

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

Types, Operators and Expressions

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

Applied C and C++ Programming

Few reminders and demos

C introduction: part 1

Outline. 1 Types. 2 union. 3 Bit operations. 4 The comma operator. 5 Multi-dimensional arrays. 6 Templates. 7 Most vexing parse

Work relative to other classes

File Handling in C. EECS 2031 Fall October 27, 2014

SECURE PROGRAMMING A.A. 2018/2019

Computers Programming Course 6. Iulian Năstac

CS201 - Lecture 1 The C Programming Language

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco

REMEMBER TO REGISTER FOR THE EXAM.

Introduction and basic C++ programming

Fundamentals of Programming

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

Data Types and Computer Storage Arrays and Pointers. K&R, chapter 5

Tutorial 1: Introduction to C Computer Architecture and Systems Programming ( )

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

CptS 360 (System Programming) Unit 2: Introduction to UNIX and Linux

UNIT- 3 Introduction to C++

PROGRAMMAZIONE I A.A. 2017/2018

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

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

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

Programming in C Quick Start! Biostatistics 615 Lecture 4

Chapter 7. Basic Types

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

Programming in C++ 5. Integral data types

C Functions. 5.2 Program Modules in C

C Programming Multiple. Choice

Algorithms, Data Structures, and Problem Solving

int main() { return 0; }

Programming in C++ 6. Floating point data types

CS16 Exam #1 7/17/ Minutes 100 Points total

Room 3P16 Telephone: extension ~irjohnson/uqc146s1.html

I BCA[ ] SEMESTER I CORE: C PROGRAMMING - 106A Multiple Choice Questions.

2. Numbers In, Numbers Out

Programming in C. Part 1: Introduction

Page 1. Today. Last Time. Is the assembly code right? Is the assembly code right? Which compiler is right? Compiler requirements CPP Volatile

Lecture 5-6: Bits, Bytes, and Integers

1.3b Type Conversion

CYSE 411/AIT681 Secure Software Engineering Topic #10. Secure Coding: Integer Security

2/9/18. Readings. CYSE 411/AIT681 Secure Software Engineering. Introductory Example. Secure Coding. Vulnerability. Introductory Example.

2/9/18. CYSE 411/AIT681 Secure Software Engineering. Readings. Secure Coding. This lecture: String management Pointer Subterfuge

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

Programming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming.

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

Transcription:

Numeric Data Types in C Kernighan & Ritchie - Chapter 2, Types, Operators, and Expressions (Binary) Integers - Counting char / unsigned char - a.k.a. signed char, unsigned char - Yes, you can do arithmetic with char's! short / short unsigned int / unsigned - a.k.a. signed int, unsigned int long / long unsigned - a.k.a. long int, long unsigned int long long int / long long unsigned int - C99, C11 not in ANSI 1

Integer Arithmetic The usual operators - + - * / % - Beware of integer division! - No "power" operator that is a "scientific" math function Bit-oriented operators - Bit-shifting: >> << - Bit-wise Boolean operations: & ^ ~ Character arithmetic This routine gets a character, does some arithmetic on it, and displays the result as both a character and a number. The numeric value turns out to be the ASCII value of the character. 2

How big are numbers? Different machine wordsizes result in different ranges for each data type. The limits.h header file defines the minimum and maximum value for each data type, on any particular machine. - CHAR_MIN, CHAR_MAX, UCHAR_MAX - SHRT_MIN, SHRT_MAX, USHRT_MAX - INT_MIN, INT_MAX, UINT_MAX - LONG_MIN, LONG_MAX, ULONG_MAX - LLONG_MIN, LLONG_MAX, ULLONG_MAX Why no UCHAR_MIN, UINT_MIN, etc.? Look at datatype sizes: /* look at datatype sizes * 2016-08-27 */ #include<stdio.h> #include<limits.h> int main(int argc, char **argv) { char line[] = "----"; char blank[] = " "; int i; unsigned u; printf("%4s %20s %20s\n", "type", "minimum", "maximum"); printf("%4s %20s %20s\n", line, line, line); printf("%4lu %#20x %#20x\n", sizeof(i), INT_MIN, INT_MAX); printf("%4s %20i %20i\n", blank, INT_MIN, INT_MAX); printf("%4s %20s %20s\n", line, line, line); printf("%4lu %#20x %#20x\n", sizeof(u), 0, UINT_MAX); printf("%4lu %20u %20u\n", sizeof(i), 0, UINT_MAX); printf("%4s %20s %20s\n", line, line, line); return 0; } 3

Add Long and Long Unsigned to the program: printf("%4lu %#20lx %#20lx\n", sizeof(l), LONG_MIN, LONG_MAX); printf("%4s %20li %20li\n", blank, LONG_MIN, LONG_MAX); printf("%4lu %#20lx %#20lx\n", sizeof(lu), 0L, ULONG_MAX); printf("%4s %20lu %20lu\n", blank, 0L, ULONG_MAX); printf("%4s %20s %20s\n", line, line, line); Add Char, Short, LLONG Results: 4

Reals - Scientific float, double long double Real operators: + - * / Scientific functions - pow(), sin(), exp(), log(),... many functions available - #include <math.h> - compile with "-lm" flag» gcc -Wall -o foo foo.c -lm» the flag must go last on the line Reals - Scientific float, double long double Real operators: + - * / Scientific functions - pow(), sin(), exp(), log(),... long double pi = many functions available 3.1415926535 long double area = pi * r*r -10.05 3.1415926535 - #include <math.h> - compile with "-lm" flag» gcc -Wall -o foo foo.c -lm» the flag must go last on the line 5

Project sine-cosine plotter Function to draw line proportional to numeric value Beat value multiplication factor for cosine() function y = sin(x) * cos(beats*x) Sinecosine plotter Features: - Prototype - Cmd-line arguments - Math library - Non-zero return value (2013 version) 6

Sinecosine plotter This function abstracts out the work of displaying a value as a line of dashes, from the work of calculating the value. Features: - Initial value for a local variable - Conversion specifier with width.precision modifier Horizontal Sine-Cosine Convert plot to more-standard horizontal display Each row of output reflects all y-values, so all y-values must be calculated (and saved) before any output Output function "drawrows()" determines character to print in each column based on corresponding y value 7

Horizontal sincosine - main() header material Horizontal sincosine - main() body 8

Horizontal sin-cosine - drawrows() /* Print y-values array horizontally * 2016-09-16 */ #include<stdio.h> #include<math.h> // round() void drawrows(double *y, unsigned npts, int nrows, int linelength) { unsigned i, j; int p; float threshold; } for (i = 0; i < nrows; i++) { threshold = 1.0-2.0*(float)i/(float)nrows; for (j = 0; j < linelength; j++) { p = (int)round((float)npts * (float)j/(float)linelength); if (i == nrows/2) putchar('-'); else if (threshold > 0) { putchar( y[p] < 0 threshold > y[p]? ' ' : '*' ) ; } else if (threshold < 0) { putchar( y[p] > 0 (threshold < y[p])? ' ' : '*' ); } else putchar('+'); } putchar('\n'); } Type Conversions C uses casts to convert integer types to real types and vice versa Examples: - char c = a ; double realchar; realchar = (double)c; - unsigned intpi = (unsigned)3.14159; - long int x; unsigned y; x = (long int)y; Some casts are necessary; some casts aren t really needed, because the compiler can do the right thing without any help. 9

Boolean There is no Boolean type Zero (0) means "false" Non-zero means "true" - Logical operators produce One (1) for "true" Boolean values are used in if-else statements, loops, and the ternary operator Boolean values may be used in binary arithmetic operations (if you want to write obfuscated code) Boolean Operators Logical - And: && - Or: - Not:! Relational - less than: <, less than or equal to: <= - greater than: >, greater than or equal to: >= - equal to: ==, not equal to:!= 10

Assignment Operators Assignment in C is an operation that returns a value (like any other operation), and has the side-effect of changing the value of its lefthand operand. Available operators - assign: = - arithmetic-assign: += -= *= /= %= &= ^= = <<= >>= The Ternary Operator Like an if-else block that returns a value Operator:? : Example: - a = ( b > c? 2*b : c/2 )» gives a the value 2*b or c/2, depending on whether b is greater than c or not Project: hailstone sequence 11

The Hailstone sequence Collatz s conjecture: - For starting value m, this sequence always reaches 1 in a finite number of steps. True? The Comma Operator The comma operator, or sequencing operator, performs operations in a left-to-right manner, and returns the value of the right-most operation. This also makes sense if the operations have side effects (e.g. assignments). Otherwise, you might as well use separate statements. Example: swap a and b, using c c = a, a = b, b = c ; 12

Example: Bubble Sort In a Bubble sort, adjacent elements are compared, and swapped if necessary. The comparisons start at one end, step to the other end; at which point the largest (or smallest) value has bubbled to its position. This process is repeated until no further swaps occur, at which point the elements are sorted. It is generally considered an inefficient sort; but it is easy to code. And it illustrates some programming features. So let s try it. Bubble Sort - details Generate some random numbers between 0 and 1 - Store in an array - Use a #define to parameterize the array size After each bubblepass, display the array using the linedraw() function - Makes visualization easier - Also use a #define for the desired rowlength Use a do{}while loop to perform bubblepasses - At least one pass - Test on occurrence of swap(s), reported by bubblepass() 13

bubblesort solution 14