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

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

Types, Operators and Expressions

Types, Operators and Expressions

CS102: Variables and Expressions

Engineering Computing I

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

Computer System and programming in C

Arithmetic Operators. Portability: Printing Numbers

Work relative to other classes

Fundamentals of Programming

Lecture 3. More About C

C: How to Program. Week /Mar/05

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

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Chapter 3: Operators, Expressions and Type Conversion

Definition: Data Type A data type is a collection of values and the definition of one or more operations on those values.

Fundamental of Programming (C)

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

UNIT- 3 Introduction to C++

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

Java enum, casts, and others (Select portions of Chapters 4 & 5)

CS1100 Introduction to Programming

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

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

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

Reserved Words and Identifiers

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

Chapter 3 Basic Data Types. Lecture 3 1

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

Expression and Operator

Operators. Lecture 3 COP 3014 Spring January 16, 2018

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

Informatics Ingeniería en Electrónica y Automática Industrial

CSC 1107: Structured Programming

Chapter 2 - Introduction to C Programming

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

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

JAVA Programming Fundamentals

Full file at

A Fast Review of C Essentials Part I

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

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

DEPARTMENT OF MATHS, MJ COLLEGE

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

Java Notes. 10th ICSE. Saravanan Ganesh

LECTURE 3 C++ Basics Part 2

Chapter 2: Using Data

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

Chapter 12 Variables and Operators

High Performance Computing

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

Basics of Java Programming

EEE145 Computer Programming

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

Visual C# Instructor s Manual Table of Contents

Chapter 2. Lexical Elements & Operators

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

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

CS61B Lecture #14: Integers

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

Chapter 3. Fundamental Data Types

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

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Lecture 02 C FUNDAMENTALS

Getting started with Java

2/5/2018. Expressions are Used to Perform Calculations. ECE 220: Computer Systems & Programming. Our Class Focuses on Four Types of Operator in C

Values and Variables 1 / 30

Syntax and Variables

Declaration and Memory

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

SECTION II: LANGUAGE BASICS

Differentiate Between Keywords and Identifiers

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

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

Chapter 12 Variables and Operators

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

A Java program contains at least one class definition.

JAVA OPERATORS GENERAL

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

Expressions and Casting

Maciej Sobieraj. Lecture 1

C - Basic Introduction

Operators and Type Conversion. By Avani M. Sakhapara Assistant Professor, IT Dept, KJSCE

Java Programming Fundamentals. Visit for more.

COMP Primitive and Class Types. Yi Hong May 14, 2015

Computers Programming Course 5. Iulian Năstac

OBJECT ORIENTED PROGRAMMING USING C++

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

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

CS313D: ADVANCED PROGRAMMING LANGUAGE

Preview from Notesale.co.uk Page 6 of 52

Introduction to C# Applications

Chapter 7. Basic Types

Writing Program in C Expressions and Control Structures (Selection Statements and Loops)

Programming and Data Structures

Part I Part 1 Expressions

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

Expressions and Precedence. Last updated 12/10/18

CS Programming In C

Zheng-Liang Lu Java Programming 45 / 79

Transcription:

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

Variables Names of variables: Composed of letters, digits, and the underscore ( ) character. (NO spaces; use underscore instead.) First character must be a letter. At least the first 31 characters matter after that, they may not. You can t use keywords (like if, else, etc.) variable names. for Similar rules for naming functions, etc. 2

Data types C s basic types and typical sizes: char - a single byte, capable of holding one integer/character (8/16 bits) int - an integer (16/32 bits) float - single-precision floating point (32 bits) double - double-precision floating point (64 bits) NOTE: there is no basic string type. Actual size is compiler- and machine-dependent! (You can find out what the size is if you need to.) Qualifiers (e.g. unsigned, long) can be applied. An integer can be short, long, and even long long If it s unsigned it means that only positive integers can be represented. (If you try to do any operations with unsigned integers and negative integer constants, weird things might happen.) The type unsigned long long int lets you represent very large positive integers! Don t worry too much about all the different types unless you need to. 3

Variable declarations Variables must be declared at the start of a function, before use. int lower; int upper; int step; char c; char d; Variables with the same type can be grouped together: int lower, upper, step; char c, d; Variables can also be initialized in the declaration. int lower = 0, upper = 8, step = 1; char c = f, d = z ; What happens if a variable is not initialized and then used? void main() { int a; printf( "The value of a is: %d\n", a ); 4

Examples of Constants Integer constant: 1234 long int constant: 12345789 or 123456789L Integers can be specified in octal (leading zero) or hexadecimal (leading 0x or 0X): 037, 0x1f. Floating-point constant: 123.4 5

Character constants All characters are represented as integers (usually signed), and can be treated as integers. Escape codes correspond to characters, for use in single-quotes: Examples: \n (newline), \\ (backslash), \" (double quote) Example use: char a = \n ; Variables of type char can be thought of as either a character of an integer. printf( "%c", a ); /* a is printed */ printf( "%d", a ); /* 97 is printed */ printf( "%c", 97 ); /* a is printed */ printf( "%d", 97 ); /* 97 is printed */ Lower-case letters, upper-case letters, digits consecutive a == 97, b == 98,..., z == 122 A == 65, B == 66,..., Z == 90 0 == 48, 1 == 49,..., 9 == 57 Some more examples of the integer values corresponding to character constants: & == 38, * == 42, \n == 10, \\ == 92,... 6

char Example void main() { char i; printf( "Here s the alphabet, in lower-case:\n" ); for( i = 97; i <= 122; i++ ) { printf( "%c", i ); printf( "\n\nhere s the alphabet, in upper-case:\n" ); for( i = 65; i <= 90; i++ ) { printf( "%c", i ); void main() { char i; printf( "Here s the alphabet, in lower-case:\n" ); for( i = a ; i <= z ; i++ ) { printf( "%c", i ); printf( "\n\nhere s the alphabet, in upper-case:\n" ); for( i = A ; i <= Z ; i++ ) { printf( "%c", i ); 7

String constants Strictly speaking, there is no string type, so there can t be any string constants. (A string is represented as an array of characters.) Fortunately, C lets us deal with strings as if they were constants, so that they can be passed to functions that do things with strings. Just put the string in doublequotes: Example: "A string" is a string. The statement printf( "A string" ); would print that string. You ll never see anything like String s = "A string";. There is no string type, and the char* type that is used for strings does NOT do what you might expect given this kind of an assignment. We ll revisit these issues in more detail later in the course. 8

Type Conversions C is very flexible with type conversions. If an operator has operands of different types, they are converted according to a small number of rules. Automatic conversions occur when a narrower operand can be converted into a wider one. Example: adding a short and a long will cause the short to be converted automatically. (See rules on K&R, p. 44 for details.) Keep in mind that a char is just a small integer, so you can do arithmetic operations: e.g., c - a is 2. (No type conversion required!) Conversions also occur when you try to assign a variable of one type to another. Be careful the new assigned variable might be different! Example: if x is float and i is int, then the assignment i = x will truncate any fractional part of x. 9

Casting You can explicitly cast a variable of one type to be a variable of another type. This is useful if you aren t sure how conversion will work, or you want to force conversion to happen in a specific way. Example: int a=15, b=10; double x; x = a / b; /* x is now 1.0 */ x = (double) a / (double) b; /* x is now 1.5 */ Casting ensures floating point division rather than integer division (which truncates the result so that the type is still integer). 10

Enumeration constants An enumeration is a way to specify a list of constant integer values: enum color { red, blue, green ; Unless specified explicitly, the first name in an enum has value 0, the second one 1, etc. Example. void main() { enum color { red, blue, green ; int fave; printf( "0=red,1=blue,2=green" ); printf( "Enter the number of your favorite:" ); scanf( "%d", &fave ); if( fave == red ) { printf( "Red is also my favorite.\n" ); When explicit values are provided, unspecified values continue in progression from the most recent specified value. enum month { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC ; 11

Printing a float Simple form: Using printf printf( "%f", 3.141592653 ); Fancy form: printf( "%6.2f", 3.141592653 );...result: two spaces followed by 3.14 6 specifies minimum field width: at least 6 characters will be printed, with spaces added if necessary 2 specifies maximum number of digits to be printed after the decimal point Printing an int as an octal number printf( "%o\n", 17 );...result: 21 Printing an int as a hexadecimal number printf( "%x\n", 31 );...result: 1f Use %X for upper-case letters 12

Operators Recall the relational operators (>, >=, <, <=), equality operators (==,!=), and the logical operators (!, &&, ). C has a number of arithmetic operators. Assignment operator: = Binary arithmetic operators: +, -, *, /, % Can be applied to int, float, or double, except for % which can only be applied to ints. % is the modulus or mod operator: a % b is equal to the remainder when a is divided by b. We won t worry about what happens on non-positive values (implementation dependent). Example: 8 % 3 == 2. Unary arithmetic operator: -. Example: x = -y; Shortcut operators: +=, -=, *=, /= x += 2; /* equivalent to x = x + 2; */ x *= 2; /* equivalent to x = x * 2; */ Increment/decrement operators: ++, -- x++; /* acts like x = x + 1; */ x--; /* acts like x = x - 1; */ 13

++ and : tricky expressions Both x++ and ++x are expressions. The expression x++ acts like x, and ++x acts like the expression x+1. What s special is the side effect: evaluating these expressions causes x to be incremented by 1. int a = 10, b, c; b = a++; /* a is now 11, b is 10 */ c = ++b; /* a, b, c are all 11 */ For clarity, try not to mix ++ or -- into complicated expressions. Note that the expression that ++ or -- is applied to must be an lvalue, e.g. a variable. (x + 2)++; /* no good! */ The left side of an assignment statement must be an lvalue; hence the l in lvalue. x + 2 = 8; /* no good! */ The result of applying ++ or -- to an lvalue is NOT an lvalue. (x++)++; /* no good! */ 14

Bitwise operators Six operators for bit manipulation which can only be applied to integral operands (e.g., variables of type int or char): Bitwise AND (&) Bitwise inclusive OR ( ) Bitwise exclusive OR (^) Left shift (<<) Right shift (>>) One s complement (~) All binary except for one s complement. Left shifting fills vacated bits with zero. But be careful! Right shifting a signed quantity (e.g. int variable) may fill vacated bits with sign bits on some machines. Can be used with shortcut operators, e.g. =, ~=, <<=, etc. See PCP, Chapter 11 for more details. (We probably won t use bit operations again in this class, but it s good to know about them.) 15

Order of Evaluation How are expressions with many operators evaluated? Two considerations: Precedence How is 1 + 2 * 3 evaluated? Is it (1 + 2) * 3, or 1 + (2 * 3)? It s the latter: the * operator has higher precedence than the + operator. Parentheses must be used if we want the addition to be performed first. Associativity What about expressions containing operators at the same precedence level? E.g., (12 / 6 * 2) or (5-3 - 1)? These parse as ((12 / 6) * 2) and ((5-3) - 1): they are left associative. (Most operators are left associative.) See table on p. 53 of K&R. What about x += y = z;? 16

True or false? void main() { int a = -2, b = -1, c = 0; if( a < b < c ) printf( "True.\n" ); else printf( "False.\n" ); if (a >= b >= c) printf( "True.\n"); else printf( "False.\n"); Be careful! Use parentheses! 17