Overview of C. Basic Data Types Constants Variables Identifiers Keywords Basic I/O

Similar documents
Arithmetic type issues

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

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

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

UNIT- 3 Introduction to C++

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

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

Basic Types and Formatted I/O

THE FUNDAMENTAL DATA TYPES

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

6.096 Introduction to C++ January (IAP) 2009

Basics of Java Programming

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

JAVA Programming Fundamentals

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

Program Fundamentals

CS61B Lecture #14: Integers. Last modified: Wed Sep 27 15:44: CS61B: Lecture #14 1

CS102: Variables and Expressions

Programming in C++ 4. The lexical basis of C++

ISA 563 : Fundamentals of Systems Programming

Computer System and programming in C

DEPARTMENT OF MATHS, MJ COLLEGE

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

Work relative to other classes

Fundamental of Programming (C)

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

Operators. Java operators are classified into three categories:

CSC 1107: Structured Programming

Fundamental of C programming. - Ompal Singh

Mechatronics and Microcontrollers. Szilárd Aradi PhD Refresh of C

Lecture 3. More About C

C++ character set Letters:- A-Z, a-z Digits:- 0 to 9 Special Symbols:- space + - / ( ) [ ] =! = < >, $ # ; :? & White Spaces:- Blank Space, Horizontal

Java Notes. 10th ICSE. Saravanan Ganesh

CS61B Lecture #14: Integers

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

Chapter 6 Primitive types

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

Java Programming Fundamentals. Visit for more.

Chapter 2: Basic Elements of C++

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

Full file at

ANSI C Programming Simple Programs

Declaration. Fundamental Data Types. Modifying the Basic Types. Basic Data Types. All variables must be declared before being used.

Computers Programming Course 5. Iulian Năstac

C++ Programming Basics

Programming in C++ 5. Integral data types

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

LECTURE 3 C++ Basics Part 2

QUIZ: What value is stored in a after this

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

Visual C# Instructor s Manual Table of Contents

Chapter 3: Operators, Expressions and Type Conversion

BASIC ELEMENTS OF A COMPUTER PROGRAM

A flow chart is a graphical or symbolic representation of a process.

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Programming for Engineers Introduction to C

Chapter 2: Using Data

Programming, numerics and optimization

PYTHON- AN INNOVATION

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

Information Science 1

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

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

Fundamentals of Programming

Types, Operators and Expressions

Programming in C++ 6. Floating point data types

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

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Chapter 2. Lexical Elements & Operators

Arithmetic Operators. Portability: Printing Numbers

Operators. Lecture 3 COP 3014 Spring January 16, 2018

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

Types, Operators and Expressions

Chapter 3 : Informatics Practices. Class XI ( As per CBSE Board) Python Fundamentals. Visit : python.mykvs.in for regular updates

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

Engineering Computing I

Chapter 3. Fundamental Data Types

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

PART I. Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++.

ME 461 C review Session Fall 2009 S. Keres

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

C: How to Program. Week /Mar/05

Programming in C and Data Structures [15PCD13/23] 1. PROGRAMMING IN C AND DATA STRUCTURES [As per Choice Based Credit System (CBCS) scheme]

Language Fundamentals Summary

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

C Programming Language (Chapter 2 of K&R) Variables and Constants

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Princeton University. Computer Science 217: Introduction to Programming Systems. Data Types in C

Introduction to Programming

Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. C Data Types

Data Types Literals, Variables & Constants

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

Data Representa5on. CSC 2400: Computer Systems. What kinds of data do we need to represent?

GO - OPERATORS. This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

Goals of C "" The Goals of C (cont.) "" Goals of this Lecture"" The Design of C: A Rational Reconstruction"

Full file at

Introduction to C Language

Numerical Computing in C and C++ Jamie Griffin. Semester A 2017 Lecture 2

Chapter 2 - Introduction to C Programming

CMPT 125: Lecture 3 Data and Expressions

Transcription:

Overview of C Basic Data Types Constants Variables Identifiers Keywords Basic I/O NOTE: There are six classes of tokens: identifiers, keywords, constants, string literals, operators, and other separators. Blanks, horizontal and vertical tabs, newlines, form feeds and comments (collectively, white space ) are ignored except as they separate tokens. Some white space is required to separate otherwise adjacent identifiers, keywords, and constants 19

Basic Data Types Integer Types Char smallest addressable unit; each byte has its own address Short not used so much Int default type for an integer constant value Long do you really need it? Floating point Types are inexact Float single precision (about 6 digits of precision) Double double precision (about 15 digits of precision) constant default unless suffixed with f Note that variables of type char are guaranteed to always be one byte. There is no maximum size for a type, but the following relationships must hold: sizeof(short) <= sizeof(int) <= sizeof(long) sizeof(float) <= sizeof(double) <= sizeof(long double) 20

Derived types (fyi) Beside the basic types, there is a conceptually infinite class of derived types constructed from the fundamental types in the following ways: arrays of objects of a given type; functions returning objects of a given type; pointers to objects of a given type; structures containing a sequence of objects of various types; unions capable of containing any of one of several objects of various types. In general these methods of constructing objects can be applied recursively An array of pointers An array of characters (i.e. a string) Structures that contain pointers 21

Constants Special characters Not convenient to type on a keyboard Use single quotes i.e. \n Looks like two characters but is really only one \a alert (bell) character \\ backslash \b backspace \? question mark \f formfeed \ single quote \n newline \" double quote \r carriage return \ooo octal number \t horizontal tab \xhh hexadecimal number \v vertical tab 22

Symbolic constants A name that substitutes for a value that cannot be changed Can be used to define a: Constant Statement Mathematical expression Uses a preprocessor directive #define <name> <value> No semi-colon Coding style is to use all capital letters for the name Can be used any place you would use the actual value All occurrences are replaced when the program is compiled Examples (see link below): The use of EXIT_SUCCESS in hello.c code (see stdlib.h) #define PI 3.141593 #define TRUE 1 #define floatingpointnum float http://www.cprogrammingexpert.com/c/tutorial/fundamentals/symbolic_constant_c _programming_language.aspx 23

Variable Declarations Purpose: define a variable before it is used. Format: type identifier [, identifier] ; Initial value: can be assigned int i, j, k; char a, b, c = D ; int i = 123; float f = 3.1415926535; double f = 3.1415926535; strings later array of characters Type conversion: aka, type casting Coercion, be very cautious. (type) identifier; int i = 65; /* what if 258 */ char a; /* range -128 to 127 */ a = (char) i; /* What is the value of a? */ INSTANCE VARIABLE In object-oriented programming with classes, an instance variable is a variable defined in a class (i.e. a member variable), for which each object of the class has a separate copy. They live in memory for the life of the class. 24

Variable vs Identifier An identifier, also called a token or symbol, is a lexical token that names an entity An entity can be: variables, types, labels, functions, packages, etc. Naming entities makes it possible to refer to them A variable Allows access and information about what is in memory i.e. a storage location A symbolic name (an identifier) that is associated with a value and whose associated value may be changed The usual way to reference a stored value 25

Identifier Naming Style Rules for identifiers a-z, A-Z, 0-9, and _ Case sensitive The first character must be a letter or _ Keywords are reserved words, and may not be used as identifiers Identifier Naming Style Separate words with _ or capitalize the first character Use all UPPERCASE for symbolic constant, macro definitions, etc Be consistent Be meaningful Sample Identifiers i0, j1, abc, stu_score, st, data_t, MAXOF, MINOF... 26

Keywords Purpose: reserves a word or identifier to have a particular meaning The meaning of keywords and, indeed, the meaning of the notion of keyword differs widely from language to language. You shouldn't use them for any other purpose in a C program. They are allowed, of course, within double quotation marks. 27

Arithmetic operators Mathematical Symbols + - * / % addition, subtraction, multiplication, division, modulus Works for both int and float + - * / / operator performs integer division if both operands are integer i.e. truncates; otherwise, float % operator divides two integer operands with an integer result of the remainder Precedence left to right () always first * / % + - 28

Binary operators << left-shift wait for these later >> right-shift & bitwise AND bitwise OR ^ bitwise exclusive-or && logical AND logical OR < less than > greater than <= less than or equal >= greater than or equal == equals!= does not equal BITWISE OPERATORS: 0 is FALSE 1 is TRUE Result: 0 is false; everything else is true LOGICAL OPERATORS: 0 is FALSE Everything else is TRUE Note: C has no keywords as true or false. They are non-zero or zero values, usually 1 or 0. `OR', `AND', and `NOT': differences between bitwise and logical operators. 29

Unary operators +1 positive 1-1 negative 1 ~i one's complement (bitwise complement)!i logical negation (i.e., 1 if i is zero, 0 otherwise) ++i adds one to i, and returns the new value of i --i subtracts one from i, and returns the new value of i i++ adds one to i, and returns the old value of i i-- subtracts one from i, and returns the old value of i EXAMPLES i = 20 = 0b0000 10100 ~i = 1111 01011!i = 0 ++i = 21, i = 21 --i = 19, i = 19 i++ = 20, i = 21 i-- = 20, i = 19 30

Assignment operators = assignment += addition assignment -= subtraction assignment *= multiplication assignment /= division assignment %= remainder/modulus assignment &= bitwise AND assignment = bitwise OR assignment ^= bitwise exclusive OR assignment <<= left shift assignment >>= right shift assignment EXAMPLES i += 1 i = i + 1 i &= 1 i = i & 1 i <<= 1 i = i << 1 Assignment operators take the value on the right and place it into the variable on the left. C provides more derivatives by combining computation and assignment together. Note the difference between assignment and equal operators. Don't make the mistake of using '=' when you meant '=='! 31

Operator Precedence https://www.cs50.net/resources/cppreferenc e.com/operator_precedence.html See handout Do in-class exercises 32

Arithmetic type issues Type casting - EXPLICIT A way to convert a variable from one data type to another data type Uses a cast operator (type-name) (type-name) expression Type combination and promotion - IMPLICIT ( a 32) = 97 32 = 65 = A Smaller type (char) is promoted to be the same size as the larger type (int) Determined at compile time - based purely on the types of the values in the expressions Does not lose information convert from type to compatible large type 33

C type-casting The usual arithmetic conversions are implicitly performed to cast their values in a common type. Compiler first performs integer promotion, if operands still have different types then they are converted to the type that appears highest in the following hierarchy 34

Arithmetic type conversions Usual Arithmetic Conversions Many operators cause conversions and yield result types in a similar way. The effect is to bring operands into a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions. If either operand is long double, the other is converted to long double. If either operand is double, the other is converted to double. If either operand is float, the other is converted to float. Otherwise, the integral promotions are performed on both operands; If either operand is unsigned long int, the other is converted to unsigned long int. If one operand is long int and the other is unsigned int, the effect depends on whether a long int can represent all values of an unsigned int; if so, the unsigned int operand is converted to long int; if not, both are converted to unsigned long int. If one operand is long int, the other is converted to long int. If either operand is unsigned int, the other is converted to unsigned int. Otherwise, both operands have type int. NOTE: There are two changes here. First, arithmetic on float operands may be done in single precision, rather than double; the first edition specified that all floating arithmetic was double precision. Second, shorter unsigned types, when combined with a larger signed type, do not propagate the unsigned property to the result type; in the first edition, the unsigned always dominated. The new rules are slightly more complicated, but reduce somewhat the surprises that may occur when an unsigned quantity meets signed. Unexpected results may still occur when an unsigned expression is compared to a signed expression of the same size. 35

Arithmetic expressions - Truncation Pitfall -- int vs. float Arithmetic Here's an example of the sort of code where int vs. float arithmetic can cause problems. Suppose the following code is supposed to scale a homework score in the range 0..20 to be in the range 0..100. { int score;...// suppose score gets set in the range 0..20 somehow 7 score = (score / 20) * 100; // NO -- score/20 truncates to 0... Unfortunately, score will almost always be set to 0 for this code because the integer division in the expression (score/20) will be 0 for every value of score less than 20. The fix is to force the quotient to be computed as a floating point number... score = ((double)score / 20) * 100; // OK -- floating point division from cast score = (score / 20.0) * 100; // OK -- floating point division from 20.0 score = (int)(score / 20.0) * 100; // NO -- the (int) truncates the floating // quotient back to 0 36