elementary concepts - ulisboa · pdf file... voidindicates that the function takes no...
Post on 17-Mar-2018
221 Views
Preview:
TRANSCRIPT
Programming
Elementary Concepts
Summary} C Language Basic Concepts
} Comments, Preprocessor, Main
} Key Definitions} Datatypes} Variables} Constants} Operators} Conditional expressions} Type conversions} Precedences
Programação (Pro364511)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
Programação (Pro364511)3
Use of Comments
Programação (Pro364511)4
/*
** 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
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
Programação (Pro364511)5
Preprocessor Directives
Programação (Pro364511)6
#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
Preprocessor Directives
Programação (Pro364511)7
#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.
The main() Function
Programação (Pro364511)8
} 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
The printf() Function
Programação (Pro364511)9
printf( "Original input : %s\n", input );
} printf() is a library function declared in <stdio.h>} Syntax: printf( FormatString, Expr, Expr...)
} 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),
%d (print as integer),%f (print as floating-point)
} \n indicates a newline character
Make sure you pickthe right one!
Text line printed onlywhen \n encounteredDon’t forget \n whenprinting “final results”
return vs. exit
Programação (Pro364511)10
} 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()
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 (?:)
Programação (Pro364511)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
Programação (Pro364511)12
Four Basic Data Types
Programação (Pro364511)13
} 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
Characters
Programação (Pro364511)14
} 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 todigit - 48
Why isdigit - '0'
preferable?
Integers used as Boolean
Programação (Pro364511)15
} 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
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));
Programação (Pro364511)16
Numeric�data�types�Depending�on�the�precision�and�range�required,�you�can�use�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;�
• The�unsigned�version�has�roughly�double�the�range�of�its�signed�counterparts.�
• Signed�and�unsigned�characters�differ�only�when�used�in�arithmetic�expressions.�
• Titbit:�Flickr�changed�from�unsigned�long�(232 � 1)�to�string�two�years�ago.�
7�
Ranges of Int and Char Types
Programação (Pro364511)17
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)
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;
Programação (Pro364511)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 !!!!!
Programação (Pro364511)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
Programação (Pro364511)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
Programação (Pro364511)21
Constants} Constants are literal/fixed values assigned to variables or
used directly in expressions
Programação (Pro364511)22
Constants�
Constants�are�literal/fixed�values�assigned�to�variables�or�used�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�
10�
Constants�(contd.)�
Datatype� example� meaning�
character�’A’
’\x41’ ’\0101’
character�specified�in�hex�specified�in�octal�
string� "hello world" "hello""world"
string�literal�same�as�"hello�world"�
enumeration� enum�BOOL�{NO,YES}�enum�COLOR�{R=1,G,B,Y=10}�
NO=0,YES=1�G=2,B=3�
11�
Operators
Arithmetic�operators�
operator� meaning� examples�
+� addition�x=3+2;�/⇤constants⇤/�y+z;� /⇤variables⇤/�
x+y+2;�/⇤both⇤/�
- subtraction�3�2;�/⇤constants⇤/�
int� x=y�z;�/⇤variables⇤/�y�2�z;�/⇤both⇤/�
*� multiplication�int� x=3⇤2;�/⇤constants⇤/�int� x=y⇤z;�/⇤variables⇤/�
x⇤y⇤2;�/⇤both⇤/�
14�
Programação (Pro364511)23
Arithmetic�operators�(contd.)�
operator� meaning� examples�
/� division�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)⇤/�
%�modulus�
(remainder)�
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⇤/�
15�
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
Programação (Pro364511)24
Relational�Operators�
Relational�operators�compare�two�operands�to�produce�a�’boolean’�result.�In�C�any�non-zero�value�(1�by�convention)�is�considered�to�be�’true’�and�0�is�considered�to�be�false.�operator� meaning� examples�
>� greater�than� 3>2;�/⇤evaluates�to� 1�⇤/�2.99>3�/⇤evaluates�to�0�⇤/�
>=� greater�than�or�equal�to�
3>=3;�/⇤evaluates�to� 1�⇤/�2.99>=3�/⇤evaluates�to�0�⇤/�
<� lesser�than� 3<3;�/⇤evaluates�to� 0�⇤/�’A’<’B’/⇤evaluates�to�1⇤/�
<=� lesser�than�or�equal�to�
3<=3;�/⇤evaluates�to� 1�⇤/�3.99<3�/⇤evaluates�to�0�⇤/�
16�
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
Programação (Pro364511)25
Relational�Operators�
Testing�equality�is�one�of�the�most�commonly�used�relational�operator�
==�operator.�
!=�
Gotchas:�
meaning�
equal�to�
not�equal�to�
examples�3==3;�/⇤evaluates�to� 1�⇤/�
’A’==’a’/⇤evaluates�to�0�⇤/�3!=3;� /⇤evaluates�to� 0�⇤/�
2.99!=3�/⇤evaluates�to� 1�⇤/�
Note�that�the�"=="�equality�operator�is�different�from�the�• "=",�assignment�operator.�Note�that�the�"=="�operator�on�float�variables�is�tricky�• because�of�finite�precision.�
17�
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)*/
Programação (Pro364511)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
Programação (Pro364511)27
Logical�operators�
operator� meaning� examples�
&&� AND� ((9/3)==3)� &&�(2⇤3==6);�/⇤evaluates�to�1�⇤/�(’A’==’a’)�&&�(3==3)�/⇤evaluates�to�0�⇤/�
||� OR� 2==3�||� ’A’==’A’;�/⇤evaluates�to�1�⇤/�2.99>=3�||� 0� /⇤evaluates�to� 0�⇤/�
!� NOT� !(3==3);� /⇤evaluates�to� 0�⇤/�!(2.99>=3)� /⇤evaluates�to� 1�⇤/�
Short�circuit:�The�evaluation�of�an�expression�is�discontinued�if�the�value�of�a�conditional�expression�can�be�determined�early.�Be�careful�of�any�side�effects�in�the�code.�Examples:�
• (3==3)� ||� ((c=getchar())==’y’).�The�second�expression�is�not�evaluated.�
• (0)� &&�((x=x+1)>0)�.�The�second�expression�is�not�evaluated.�
18�
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
Programação (Pro364511)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.
Programação (Pro364511)29
Bitwise�Operators�
operator� meaning� examples�
&� AND� 0x77�&�0x3;�/⇤evaluates�to� 0x3�⇤/�0x77�&�0x0;�/⇤evaluates�to� 0�⇤/�
|� OR� 0x700�|�0x33;�/⇤evaluates�to� 0x733�⇤/�0x070�|�0� /⇤evaluates�to� 0x070�⇤/�
ˆ� XOR� 0x770�^�0x773;�/⇤evaluates�to�0x3�⇤/�0x33�^�0x33;�/⇤evaluates�to� 0�⇤/�
«� left�shift� 0x01<<4;�/⇤evaluates�to�0x10�⇤/�1<<2;�/⇤evaluates�to� 4�⇤/�
»� right�shift� 0x010>>4;�/⇤evaluates�to�0x01�⇤/�4>>1�/⇤evaluates�to�2�⇤/�
Notes:�• AND�is�true�only�if�both�operands�are�true.�• OR�is�true�if�any�operand�is�true.�• XOR�is�true�if�only�one�of�the�operand�is�true.�
21�
Bitwise Operators
Programação (Pro364511)30
} 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
} Unary operator ~} Perform one’s complement of the operand: change each 0 to a
1 and vice versa
& 0 1
0 0 0
1 0 1
| 0 1
0 0 1
1 1 1
^ 0 1
0 0 1
1 1 0
Example: Binary Operators
Programação (Pro364511)31
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
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 */
Programação (Pro364511)32
Assignment Operators
Operator Description Example
= Simple assignment operator, Assigns values from right side operands to left side operand
C = A + B; will assign value of A + B into C;
+=Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand
C += A; is equivalent to C = C + A;
-=Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand
C -= A; is equivalent to C = C – A;
*=Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand
C *= A; is equivalent to C = C * A;
/=Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand
C /= A; is equivalent to C = C / A;
%=Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand
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
Programação (Pro364511)34
Casting: Converting One Type to Another
Programação (Pro364511)35
} 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
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
Programação (Pro364511)36
Type Conversions} Operators with different type} Conversion rules according to the datatypes
Programação (Pro364511)37
Operator 1 Operator 2 Conversion Result
int int none intint float op1 int → float float
float int op2 int → float floatfloat float none float
Precedence, associativity, evaluation order
Programação (Pro364511)38
} Precedence: given two operators of different types, which is evaluated first?
} Associativity: given a sequence of instances of the sameoperator, 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?
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’)∗/
Programação (Pro364511)39
1 ! + - (unary operators) Highest
2 * / %
3 + - (sum and subtraction)
4 < > <= >=
5 == !=
6 &&
7 ||
8 = (assignment) Lowest
Precedences
Programação (Pro364511)40
Example: Expression evaluation
Programação (Pro364511)41
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
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
Programação (Pro364511)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)))
Programação (Pro364511)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);
Programação (Pro364511)44
Review: Printf Placeholders} The format specification has the following components
} %[flags ][ width ][. precision ][ length]<type>
Programação (Pro364511)45
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 % */
Review: Printf Placeholders
Programação (Pro364511)46
printf�format�specification�(cont.)�
%[flags][width�][.�precision ][ modifier]<type>�width:�
format� output�printf�("%d",10)� "10"�printf�("%4d",10)� bb10�(b:space)�printf�("%s","hello")� hello�printf�("%7s","hello")� bbhello�
13�
} %[flags ][ width ][. precision ][ length]<type>
printf�format�specification�(cont.)�
%[flags][width�][.�precision ][ modifier]<type>�precision:�
format� output�printf�("%.2f,%.0f,1.141,1.141) 1.14,1�printf�("%.2e,%.0e,1.141,100.00) 1.14e+00,1e+02�printf�("%.4s","hello")� hell�printf�("%.1s","hello")� h�
15�
printf�format�specification�(cont.)�
%[flags][width�][.�precision ][ modifier]<type>�modifier:�
modifier� meaning�h� interpreted�as�short.�Use�with�i,d,o,u,x�l� interpreted�as�long.�Use�with�i,d,o,u,x�L� interpreted�as�double.�Use�with�e,f,g�
16�
To Review} Marques de Sá
} Capítulo 2
} Damas} Capítulo 1 e 2
} Kernighan and Ritchie} Chapter 2
Programação (Pro364511)47
top related