Programming. Elementary Concepts

Similar documents
Fundamental of Programming (C)

Fundamentals of Programming

C expressions. (Reek, Ch. 5) 1 CS 3090: Safety Critical Programming in C

Reserved Words and Identifiers

Work relative to other classes

UNIT- 3 Introduction to C++

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

Computer System and programming in C

Types, Operators and Expressions

Types, Operators and Expressions

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

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

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

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

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

CS107, Lecture 3 Bits and Bytes; Bitwise Operators

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

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

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

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

SECTION II: LANGUAGE BASICS

Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

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

Number Systems, Scalar Types, and Input and Output

Expression and Operator

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

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

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators

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

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

Chapter 3: Operators, Expressions and Type Conversion

Computers Programming Course 5. Iulian Năstac

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

A Java program contains at least one class definition.

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

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

ANSI C Programming Simple Programs

6.096 Introduction to C++ January (IAP) 2009

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

Chapter 2: Basic Elements of C++

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

Lecture 3. More About C

A First Program - Greeting.cpp

Arithmetic and Bitwise Operations on Binary Data

Variables and literals

Basic Types and Formatted I/O

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

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

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

COMP2121: Microprocessors and Interfacing. Number Systems

Arithmetic Operators. Portability: Printing Numbers

C: How to Program. Week /Mar/05

Java Notes. 10th ICSE. Saravanan Ganesh

Lecture 02 C FUNDAMENTALS

High Performance Computing in C and C++

Operators. Lecture 3 COP 3014 Spring January 16, 2018

Programming in C++ 5. Integral data types

DEPARTMENT OF MATHS, MJ COLLEGE

Programming and Data Structures

A Fast Review of C Essentials Part I

JAVA OPERATORS GENERAL

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

Course Outline Introduction to C-Programming

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

XSEDE Scholars Program Introduction to C Programming. John Lockman III June 7 th, 2012

CS313D: ADVANCED PROGRAMMING LANGUAGE

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

Visual C# Instructor s Manual Table of Contents

CSCE 110 PROGRAMMING FUNDAMENTALS

Have the same meaning as variables in algebra Single alphabetic character Each variable needs an identifier that distinguishes it from the others a =

CSC 1107: Structured Programming

Unit 3. Operators. School of Science and Technology INTRODUCTION

Lexical Considerations

JAVA Programming Fundamentals

Types, Variables, and Constants

Language Reference Manual simplicity

ME 461 C review Session Fall 2009 S. Keres

Chapter 2 - Introduction to C Programming

The component base of C language. Nguyễn Dũng Faculty of IT Hue College of Science

Engineering Computing I

Chapter 7. Basic Types

1.3b Type Conversion

Fundamental of C programming. - Ompal Singh

CS107, Lecture 2 Bits and Bytes; Integer Representations

BASIC ELEMENTS OF A COMPUTER PROGRAM

Computers Programming Course 6. Iulian Năstac

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

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

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

Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. C Data Types

Introduction to C Language

LECTURE 3 C++ Basics Part 2

Operators & Expressions

Hardware: Logical View

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

The C language. Introductory course #1

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

CSC 1214: Object-Oriented Programming

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

Transcription:

Programming Elementary Concepts

Summary } C Language Basic Concepts } Comments, Preprocessor, Main } Key Definitions } Datatypes } Variables } Constants } Operators } Conditional expressions } Type conversions } Precedences 2

Review: C Programming Language } C is a fast, small, general-purpose, platform independent programming language } C is used in several applications: } Compilers and interpreters } Operating systems } Database systems } Microcontrollers } etc. } C is a structured, static compiled and typed } "C is quirky, flawed, and an enormous success." Ritchie 3

Use of Comments /* ** This program reads input lines from the standard input and prints ** each input line, followed by just some portions of the lines, to ** the standard output. ** ** The first input is a list of column numbers, which ends with a ** negative number. The column numbers are paired and specify ** ranges of columns from the input line that are to be printed. ** For example, 0 3 10 12-1 indicates that only columns 0 through 3 ** and columns 10 through 12 will be printed. */ } Only /* */ for comments in C89 } Do not nest /* */ comments within comments } /* is matched with the very next */ that comes along } Support for // comments in C99 4

Use of Comments } Possible uses: } Identify the authors } Describe the program } Describe the code and the variables } Explain decisions } Hide code } Can appear in any place 5

Preprocessor Directives #include <stdio.h> #include <stdlib.h> #include <string.h> } The #include directives paste the contents of the files stdio.h, stdlib.h and string.h into your source code, at the place where the directives appear } These files contain information about some library functions used in the program: } stdio stands for standard I/O, stdlib stands for standard library, and string.h includes useful string manipulation functions. } Can be used to include own header files 6

Preprocessor Directives #define MAX_COLS 20 #define MAX_INPUT 1000 } The #define directives performs global replacements : } every instance of MAX_COLS is replaced with 20, and every instance of MAX_INPUT is replaced with 1000. 7

The main() Function } main() is always the first function called in a program execution. int main( void ) { } void indicates that the function takes no arguments } int indicates that the function returns an integer value } Through returning some values, the program can indicate the state of termination (success vs failure) } Operating system can react accordingly 8

The printf() Function printf( "Original input : %s\n", input ); } printf() is a library function declared in <stdio.h> } Syntax: printf( FormatString, Expr, Expr...) 9 } FormatString: String of text to print } Exprs: Values to print } FormatString has placeholders to show where to put the values (note: #placeholders should match #Exprs) } Placeholders: %s (print as string), %c (print as char), Make sure you pick the right one! %d (print as integer), %f (print as floating-point) } \n indicates a newline character Text line printed only when \n encountered Don t forget \n when printing final results

return vs. exit } The return statement in main(): return EXIT_SUCCESS; } EXIT_SUCCESS is a constant defined in stdlib } Returning this value means successful termination. puts( Last column number is not paired. ); exit( EXIT_FAILURE ); } EXIT_FAILURE is another constant, signifying that something wrong happened requiring termination } exit differs from return in that execution terminates immediately control is not passed back to the calling function main() 10

Definitions } The datatype of an object in memory determines the set of values it may have and what operations supports } C is a weakly typed language. It allows implicit conversions as well as forced (potentially dangerous) casting } Operators specify how an object can be manipulated and can be: } Unary(e.g., -,++), Binary (e.g., +,-,*,/), Ternary (?:) 11

Definitions } An expression in a programming language is a combination of values, variables, operators and functions } Changes state, print value, etc. } A variable is as named link/reference to a value stored in the system s memory } Consider: int x=0, y=0; y=x+2; } x, y are variables } y=x+2 is an expression } + is an operator 12

Four Basic Data Types } Integer: char, short int, int, long int, enum } Floating-point: float, double, long double } Pointer } Aggregate: arrays, struct, union } Integer and floating-point types are atomic, but pointers and aggregate types combine with other types 13

Characters } From a C perspective, a character is indistinguishable from its numeric ASCII value } The only difference is the way it s displayed } Ex: converting a character digit to its numeric value } The value of '2' is not 2 it s 50 } To convert, subtract the ASCII value of '0' (which is 48) char digit, digit_num_value;... digit_num_value = digit - '0'; Behaviorally, this is identical to digit - 48 Why is digit - '0' preferable? 14

Integers used as Boolean } There is no Boolean type } Relational operators (==, <, etc.) return either 0 or 1 } Boolean operators (&&,, etc.) return either 0 or 1, and take any int values as operands } How to interpret an arbitrary int as a Boolean value: } 0 false } Any other value true 15

Numeric Data Types } Depending on the precision and range required, several datatypes can be used: } short int: 16 bits } int: 32 bits } float: 32 bits (base + exponent) } double: 64 bits } long double: 128 bits } The sizeof() function returns the number of bytes in a data type } printf("size of char... = %d byte(s)\n", sizeof(char)); one of the following datatypes. signed unsigned short short int x;short y; unsigned short x;unsigned short int y; default int x; unsigned int x; long long x; unsigned long x; float float x; N/A double double x; N/A char char x; signed char x; unsigned char x; 16

Ranges of Int and Char Types Type Min value Max value char 0 UCHAR_MAX ( 127) signed char SCHAR_MIN ( -127) SCHAR_MAX ( 127) unsigned char 0 UCHAR_MAX ( 255) short int SHRT_MIN ( -32767) SHRT_MAX ( 32767) unsigned short int 0 USHRT_MAX ( 65535) int INT_MIN ( -32767) INT_MAX ( 32767) unsigned int 0 INT_MAX ( 65535) long int LONG_MIN ( -2147483647) LONG_MAX ( 2147483647) unsigned long int 0 ULONG_MAX ( 4294967295) 17

Declaring Variables } Must declare variables before use } Should have a datatype } Can assume different values } Variable declaration (type followed by name): } int n; } float phi; } Uninitialized, a variable assumes a default value } Variables initialized via assignment operator: } n = 10; } Can also be initialized at declaration: } float phi = 1.6180339887; } Can declare/initialize multiple variables at once: } int a, b, c = 0, d = 4; 18

Variables } A value can be assigned to a variable } Example: } a = 123 b = a + 1 } The datatype of the variable (left) should be the same as the datatype of the constant (right) } Wrong: } 123 = a } a + 2 = 123 } They are not equations!!!!! 19

Which Names to Use? } Variable names can contain letters, digits and _ } Variable names should start with letters } Keywords (e.g., for, while etc.) cannot be used as variable names } Variable names are case sensitive } int x; int X declares two different variables 20

Characters } Constant values: } a \n \t } Variable declaration: } char c; } char c1, c2; } Represents only one char: } c= c ; } a = c; } American Standard Code for Information Interchange (ASCII) } 7 bits used for internal representation } Each character has a value. Some examples: } ' ' space, '\n' newline, '\t' tab, '\b' bell, '\0' null terminator 21

Constants } Constants are literal/fixed values assigned to variables or used directly in expressions directly in expressions. Datatype example meaning int i =3; integer long l=3; long integer integer unsigned long ul= 3UL; unsigned long int i =0xA; hexadecimal int i =012; octal number float pi=3.14159 float floating point float pi=3.141f float double pi=3.1415926535897932384l double 22 Datatype example meaning character string enumeration A \x41 \0101 "hello world" "hello""world" enum BOOL {NO,YES} enum COLOR {R=1,G,B,Y=10} character specified in hex specified in octal string literal same as "hello world" NO=0,YES=1 G=2,B=3

Operators operator meaning examples / division modulus % (remainder) float x=3/2; / produces x=1 (int /) / float x=3.0/2 / produces x=1.5 (float /) / int x=3.0/2; / produces x=1 (int conversion) / int x=3%2; / produces x=1 / int y=7;int x=y%4; / produces 3 / int y=7;int x=y%10; / produces 7 / operator meaning examples + addition x=3+2; / constants / y+z; / variables / x+y+2; / both / - subtraction * multiplication 3 2; / constants / int x=y z; / variables / y 2 z; / both / int x=3 2; / constants / int x=y z; / variables / x y 2; / both / 23

Relational Operators } Relational operators compare two operands to produce a boolean result } Any non-zero value (1 by convention) is considered to be true and 0 is considered to be false } Only variables of the same datatype should be compared considered to be true and 0 is considered to be false. operator meaning examples > greater than >= greater than or equal to < lesser than <= lesser than or equal to 3>2; / evaluates to 1 / 2.99>3 / evaluates to 0 / 3>=3; / evaluates to 1 / 2.99>=3 / evaluates to 0 / 3<3; / evaluates to 0 / A < B / evaluates to 1 / 3<=3; / evaluates to 1 / 3.99<3 / evaluates to 0 / 24

Relational Operators } Testing equality is one of the most commonly used relational operator } The "==" equality operator is different from the "= assignment operator } The "==" equality operator on float variables is tricky because of finite precision quality is one of the most commonly used relational operator meaning examples == equal to 3==3; / evaluates to 1 / A == a / evaluates to 0 /!= not equal to 3!=3; / evaluates to 0 / 2.99!=3 / evaluates to 1 / 25

Example: Relational Operators } int a, b, c; } a = 10; b = 40; } c = (a > b); /* c <- 0 (false) */ } c = (a!= b); /* c <- 1 (true)*/ } c = (a <= b); /* c <- 1 (true)*/ 26

Logical Operators } Allows to concatenate several expressions } Unary Not:!(a < b) } Binary AND: (a < 10) && (a > 0) } Binary OR: (a >= 10) (a <=0) } The evaluation of an expression is discontinued if the value of a conditional expression can be determined early operator meaning examples && AND OR ((9/3)==3) && (2 3==6); / evaluates to 1 / ( A == a ) && (3==3) / evaluates to 0 / 2==3 A == A ; / evaluates to 1 / 2.99>=3 0 / evaluates to 0 /!(3==3); / evaluates to 0 /! NOT!(2.99>=3) / evaluates to 1 / Short circuit: The evaluation of an expression is discontinued 27

Increment and Decrement Operators } Increment and decrement are common arithmetic operations: } x++ is the same as x=x+1 } x-- is the same as x=x-1 } ++x is the same as x=x+1 } --x is the same as x=x-1 } y=x++ is the same as y=x; x=x+1; } x is evaluated before it is incremented. } y=x-- is the same as y=x; x=x-1; } x is evaluated before it is decremented } y=++x is the same as x=x+1;y=x; } x is evaluated after it is incremented. } y=--x is the same as x=x 1;y=x; } x is evaluated after it is decremented 28

Bitwise Operators } Operations can be performed on a bit level using bitwise operators } Make the operation on strings of eight bits (bytes) each time. 29 operator meaning examples & AND OR ˆ XOR «left shift» right shift Notes: 0x77 & 0x3; / evaluates to 0x3 / 0x77 & 0x0; / evaluates to 0 / 0x700 0x33; / evaluates to 0x733 / 0x070 0 / evaluates to 0x070 / 0x770 ^ 0x773; / evaluates to 0x3 / 0x33 ^ 0x33; / evaluates to 0 / 0x01<<4; / evaluates to 0x10 / 1<<2; / evaluates to 4 / 0x010>>4; / evaluates to 0x01 / 4>>1 / evaluates to 2 /

Bitwise Operators } Left shift: value << n } Discard the n leftmost bits, and add n zeroes to the right } Right shift: value >> n } Discard the n rightmost bits, and add n zeroes to the left } Binary operators &,, ^ } Perform bitwise and, or, xor on each bit of the operands & 0 1 0 0 0 1 0 1 } Unary operator ~ 0 1 0 0 1 1 1 1 ^ 0 1 0 0 1 1 1 0 } Perform one s complement of the operand: change each 0 to a 1 and vice versa 30

Example: Binary Operators a: 00101110 (0x2E) b: 01011011 (0x5B) ~a: 11010001 (0xD1) ~b: 10100100 (0xA4) 00101110 00101110 00101110 01011011 01011011 01011011 a&b 00001010 a b 01111111 a^b 01110101 (0x0A) (0x7F) (0x75) INT_MAX 01111111111111111111111111111111 2147483647 INT_MAX >> 16 00000000000000000111111111111111 32767 31

Assignments Operators } Another common expression found while programming in C is: var = var (op) expr } x=x+2 } x=x 20 } x=x/4 } C provides compact assignment operators that may also be used: } x+=1 / is the same as x=x+1 / } x-=1 / is the same as x=x-1 / } x =10 / is the same as x=x 10 / } x/=2 / is the same as x=x/2 */ } x%=2 / is the same as x=x%2 */ 32

Assignment Operators Operator Description Example = += -= *= /= %= Simple assignment operator, Assigns values from right side operands to left side operand Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand C = A + B; will assign value of A + B into C; C += A; is equivalent to C = C + A; C -= A; is equivalent to C = C A; C *= A; is equivalent to C = C * A; C /= A; is equivalent to C = C / A; C %= A; is equivalent to C = C % A;

Conditional Expressions } A common pattern in many programming languages is the following: } if (cond) x=<express_a>; } else } x=<express_b >; } C allows to express the same using the ternary operator?: } sign = x>=0?1:-1; } if (x>=0) } sign=1 } else } sign=-1 34

Casting: Converting One Type to Another } The compiler does a certain amount of type conversion: int a = A ; /* char literal converted to int */ } In some circumstances, you need to explicitly cast an expression as a different type by putting the desired type name in parentheses before the expression } e.g. (int) 3.14159 will return the int value 3 35

Type Conversions } When variables are converted for types with higher precision, data is preserved } int i; } float f ; } f=i+3.14159; / i is promoted to float, f=(float)i+3.14159 / } Another conversion done automatically is char int. } isupper=(c>= A && c<= Z )?1:0; / c and literal constants are converted to int / } if (! isupper) } c=c- a + A ; / subtraction is possible because of integer conversion / } As a rule (with exceptions), the compiler promotes each term in an binary expression to the highest precision operand 36

Type Conversions } Operators with different type } Conversion rules according to the datatypes Operator 1 Operator 2 Conversion Result int int none int int float op1 int float float float int op2 int float float float float none float 37

Precedence, associativity, evaluation order } Precedence: given two operators of different types, which is evaluated first? } Associativity: given a sequence of instances of the same operator, are they evaluated left-to-right or right-to-left? } Evaluation order: given an operator with a number of operands, in what order are the operands evaluated? 38

Precedence and Order of Evaluation } Some precedences: } ++,--,(cast),sizeof have the highest priority } *,/,% have higher priority than +, } ==,!= have higher priority than &&, } assignment operators have very low priority } Use () generously to avoid ambiguities or side effects associated with precendence of operators. } y=x 3+2 / same as y=(x 3)+2 / } x!=0 && y==0 / same as (x!=0) && (y==0) / } d= c>= 0 && c<= 9 / same as d=(c>= 0 ) && (c<= 9 ) / 39

Precedences 1! + - (unary operators) Highest 2 * / % 3 + - (sum and subtraction) 4 < > <= >= 5 ==!= 6 && 7 8 = (assignment) Lowest 40

Example: Expression evaluation a * b + c * d + e * f } * has precedence over + } So, multiplications are performed before additions } This leaves us with a sequence of two additions } + has left-to-right associativity, so do the leftmost addition first } Note: the multiplications can be done in any order } * has left-to-right associativity, but it doesn t matter much 41

Example: Precedences } Evaluation from left to right } 3 + 10 * 4 % 6-1 } 3 + ((10 * 4) % 6) - 1 } 3 + ( 40 % 6) - 1 } 3 + 4-1 } 6 42

Another Example: Precedence } int a, b, c, d, e, f, g; } a =1; b = 4; c=3; d= 1; e=10; f=8; } g =f = a*b+c>=c &&d<b == a!e; } g = (f=(((((a*b)+c)>=c) && } ((d<b) == a)) } (!e))) 43

Review: Writing on the Screen } int printf ( const char * format,... ); } Receives a string as a parameter } Returns the number of written characters } Takes as input a variable number of arguments } String contains placeholders } Placeholders are changed with the values of the variables } Examples: } printf( the result is: %d\n, x+12); } printf( the values are: %f and %f\n, x1, x2); 44

Review: Printf Placeholders } The format specification has the following components } %[flags ][ width ][. precision ][ length]<type> Type Meaning Example d,i integer printf( %d,10); /* prints 10 */ x,x integer(hex) printf( %c,10); /* prints 0xa */ u unsigned integer printf( %u,10); /* prints 10 */ c character printf( %c, A ); /* prints A */ s string printf( %s, hello ); /* prints hello */ f float (decimal) printf( %f, 2.3); /* prints 2.3 */ e,e float (scientific) printf( %e, 392.0); /* prints 3.92e+2 */ o unsigned octal printf( %o, 100); /* prints 144 */ % Literal % printf( %% ); /* prints % */ 45

Review: Printf Placeholders } %[flags ][ width ][. precision ][ length]<type> format output printf ("%d",10) "10" printf ("%4d",10) printf ("%s","hello") printf ("%7s","hello") bb10 (b:space) hello bbhello modifier h l L meaning interpreted as short. Use with i,d,o,u,x interpreted as long. Use with i,d,o,u,x interpreted as double. Use with e,f,g format output printf ("%.2f,%.0f,1.141,1.141) 1.14,1 printf ("%.2e,%.0e,1.141,100.00) printf ("%.4s","hello") printf ("%.1s","hello") 1.14e+00,1e+02 hell h 46

To Review } Marques de Sá } Capítulo 2 } Damas } Capítulo 1 e 2 } Kernighan and Ritchie } Chapter 2 47