variables names are made up of letters and digits first character must be a letter underscore...

32
Variables Names are made up of letters and digits First character must be a letter underscore “_” counts as a letter Upper case and lower case letters are distinct, so a and A are two different variable names, so as Tom and tom Traditionally, lower case for variable names, and all upper case for symbolic constants You cannot use keywords as variable names Use meaningful variable names use “count”, instead of “x” for counting use “year”, instead of “y” for keeping track of the year

Post on 20-Dec-2015

225 views

Category:

Documents


0 download

TRANSCRIPT

Variables• Names are made up of letters and digits

• First character must be a letter

• underscore “_” counts as a letter

• Upper case and lower case letters are distinct, so a and A are two different variable names, so as Tom and tom

• Traditionally, lower case for variable names, and all upper case for symbolic constants

• You cannot use keywords as variable names

• Use meaningful variable names

– use “count”, instead of “x” for counting

– use “year”, instead of “y” for keeping track of the year

Variable names and keywords• More examples on meaningful variable names

Sum, Total_amount, radius, Room801, average, standard_dev, StandardDev, Std

• Examples of illegal variable names

price$, 1stclass, day of the year, int• Keyword-reserved identifiers

auto, break, case, char, const, continue, default, do, double, else, enum, extern, float, for, goto, if, int, long, register, return, short, signed, sizeof, static, struct, switch, typedef, union, unsigned, void, volatile, while

Data types and their limitations

• char a single byte, capable of holding one character, we usually refer to ASCII character set (127 char)

• int an integer. For our system, an integer uses 4 bytes, therefore, it has a range of [-2G, 2G-1]

• float floating point (single-precision), uses 4 bytes and therefore has a range of 10e-38 to 10e38

• double floating point (double-precision) – 8 bytes from 10e-308 – 10e308

qualifiers: short, long, signed, unsigned; For their usages, refer to any C Manual or References.

In this class, we seldom use the above qualifiers.

Declarations• All variables must be declared before use

• A declaration specifies a type– int lower;– char c;– float total_cost;– int lower, upper;

• A variable may also be initialized in its declaration– int lower = 0;– char esc = ‘\\’;– float total_cost = 2000.0;

• For constant, the qualifier “const” can be applied to the declaration of any variable to specify that its value will not be changed

– const double PI = 3.141592653548979;

– const double e = 2.71828182845905;

Assignment statement• Assigning a value or an expression to a variablea = 5; /* assign a value 5 to variable a */

5 = a; <-- Wrong (syntax error), you cannot Wrong (syntax error), you cannot assign anything to a numberassign anything to a number

• Be careful about the R.H.S and the L.H.Sint a = 5; int a = 5;

int b = 10; int b = 10;

a = b; b = a;

The results are different!!The results are different!!

• Swapping the values between two variablesint a = 5; int a = 5;

int b = 10; int b = 10;

int temp;

temp = a; a = a + b;

a = b; b = a - b;

b = temp; a = a - b;

• Integer division truncates any fractional part

• The % operator cannot be applied to float or doubleint x = 27; int x = 28;

int y = 4; int y = 4;

int result; int result;

result = x / y; => 6=> 6 result = x / y; => 7=> 7

result = x % y; => 3=> 3 result = x % y; => 0=> 0

• Precedence: {(unary) +, -} ---> {*, /, %} ---> {+,-}

• Precedence and associativity of operators (as Table 2-1)

(fahr - 32) * 5 / 9 (fahr - 32) / 9 * 5

20 20

-12 -12

-60 -1

-6 -5

Arithmetic Operators: + - * / % (modulus)

C fahr ( )32 59

Be Careful on Integer Division!

• 25 / 2 * 2 ==> 24==> 24

• 25.0 / 2 * 2 ==> 25.000000 ==> 25.000000

• t * t / 2 not equal to t * t / 2.0 (if t is odd)

• Float to integer is by truncation, not by round-off

int x = 27; int x = 27; int x = 27;

int y = 4; int y = 4; float y = 4.0;

int result; float result; float result;

result = x / y; result = x / y; result = x / y;

result is 6 result is 6.00 result is 6.75

Relational Operators: >, >=, <, <=, ==, !=• Relational operators have lower precedence than

arithmetic operators. For example,

i < lim - 1 <---><---> i < (lim - 1)

Logical Operators: &&, ||• Expressions connected by && or || are evaluated left to

right, and evaluation stops as soon as the truth or falsehood of the result is known

• The precedence of && is higher than that of ||, and both are lower than relational and equality operators

• By definition, the numeric value of a relational or logical expression is 1 if the relation is true, and 0 if false

• The unary negation operator “!” converts a non-zero operand into 0, and a zero operand into 1

Relational and Logical Operators (examples)int i = 10; int i = 1, j = 2, k = 3;

int j; int x;

j = i > 5; x = i < 0 || j > 2;

j = i < 10; x = i > 0 || j > 2;

j = i <= 10; x = i < 0 && j > 2;

j = i + 1 <= 10; x = i > 0 && j > 2;

float p = 10.0; x = (i > 0) && (j >= 2);

float q = 5.0; x = (i > 0) && (j > 2) || (k == 3);

j = p >= 0.0; x = (i > 0) || (j > 2) && (k == 3);

j = p < 0.0; A B (A&&B)(A||B)!A !(A&&B) !A&&B

j = 0.0 < p - q; T T T T F F F

j = i == 10; T F F T F T F

j = i + 1 != 10; F T F T T T T

j = i != 10 + 1; F F F F T T F

Type Conversions (Basic Conversion in C)main()

{

float f1 = 123.456, f2;

int i1, i2 = -150;

char c = ‘a’;

i1 = f1; /* i1 = 123 */

f1 = i2; /* f1 = -150.000000 */

f1 = i2 / 100; /* f1 = -1.000000 */

f2 = i2 / 100.0; /* f2 = -1.500000 */

i1 = 5;

i1 = 10;

printf(“%d”, i1); /* i1 = 10 */

i1 = i1 + 6;

printf(“%d”, i1); /* i1 = 16 */

}

Increment and Decrement Operators• i = i + 1; can be written as i++; or ++i;

• In both cases, the effect is to increment variable i

• i++ increments i after its value has been used

• ++i increments i before its valie is used

• Why and what is the difference?int i = 5, x; int i = 5, x;

x = i++; x = ++i;

printf(“x=%d i=%d\n”, x, i); printf(“x=%d i=%d\n”, x, i);

Program output:

x=5 i=6 x=6 i=6

• Short-cut of:x = i++; => x = i; x = ++i; => i = i + 1;

i = i + 1; x = i;

Assignment Operators and Expressions• Assignment operators: +=, -=, *=, /=, %=, ...• expression1 = (expression1) operator (expression2) can be written

as expression1 operator= expression2

• i = i + 2; can be written as i += 2;• stock -= 100; is equivalent to

stock = stock - 100;• Be careful, x *= y + 1; means x = x * (y + 1); not x = x * y + 1;

• Why I don’t like it:sum += count++; =>=> sum += count; =>=> sum = sum + count;

count = count + 1; count = count + 1;

• How about “sum += ++count;” ?

Control Flow• Statements and Blocks– An expression such as x = 0 or i++ or printf(...)

becomes a statement when it is followed by a semi-colon

– In C, the semi-colon is a statement terminator

– Braces { and } are used to group declarations and statements together into a compound statement, or block, so that they are syntactically equivalent to a single statement

– No semi-colon after } that ends a block– Statement: statement; or { statement1;

statement2; . . .

statementN;

}

The IF Statement

if (expression) statement1

if (expression) statement1 else statement2

• The expression is evaluated; If it is true, statement1 is executed

• If the expression is false, and if there is an else part, statement2 is executed

• If the IF statement is simply testing the numeric value of an expression, you can simplify the syntax

if (expression != 0)

becomesif (expression)

• IF statements can be nested; That means there is an IF statement inside an IF statement

A Simple Program on IF statements

#include <stdio.h> if (tall)

main() if (heavy)

{ printf(“football player”);

int sex, height, weight; else

int tall, heavy; printf(“basket ball player”);

..... else

if (sex == 1) if (heavy)

{ printf(“TV watcher”);

printf(“He can be a “); else

if (height > 175) printf(“ice skater”);

tall = 1; }

else }

tall = 0;

if (weight > 200)

heavy = 1;

else

heavy = 0;

More on IF statementsif (!heavy) printf(“ice skater”);

else printf(“TV watcher”);

is the same asif (heavy) printf(“TV watcher”);

else printf(“ice skater”);

• Ambiguity in an IF statementif (n > 0) if (n > 0)

if (a > b) if (a > b)

z = a; z = a;

else else

z = b; z = b;

• Associating the else with the closest previous else-less IF statement

• If that is not you want, braces must be used

Nested IF statements#include <stdio.h>

main()

{

int score;

printf(“Please type in your score:”);

scanf(“%d”, &score);

printf(“Your grade is a “);

if (score >= 90) printf{“A”);

else

if (score >= 80) printf(“B”);

else

if (score >=70) printf(“C”);

else

if (score >=50) printf(“D”);

else

if (score >= 40) printf(“D”);

else

printf(“F”);

}

Switch Statementswitch (expression){

case const-expr1: statements1

case const-expr2: statements2

.....

case const-exprN: statementsN

default: statements(N+1)

}

• The switch statement is a multi-way decision that test whether an expression matches one of a number of constant integer values, and branches accordingly

• default is executed if there is no match• default is optional

• The break statement causes an immediate exit from the switch statement

switch VS. ifTry to write a program that print the name of the operation for

that operatorif (op == ‘+’) printf(“addition”);

else if (op == ‘-’) printf(“subtraction”);

else if (op == ‘*’) printf(“multiplication”);

else if (op == ‘/’) printf(“division”);

else if (op == ‘%’) printf(“mod...

when there are more operators like, !, &, |; you can run outof space, and have to type on the next line. But for the switch statement, we can have

switch(op){

case ‘+’: printf(“addition”); break;

case ‘-’: printf(“subtraction”); break;

case ‘*’: printf(“multiplication”); break;

...

default : break;

}

The break Statement inside switchint num_count = 0, num_char = 0;

char ch;

while ((ch = getchar()) != EOF){

switch (ch){

case ‘1’:

case ‘2’:

case ‘3’:

case ‘4’:

...

case ‘9’:

case ‘0’: num_count++;

default : num_char++;

break;

}

}

Loops---while statement• Statement structurewhile (expression) statementsAs mentioned in the previous lectures,statements:=> statement; or { statement1; statement2; ... statementN; }• The expression is evaluated• If the expression is true (non-zero), the statements are

executed and expression is re-evaluated• Until the expression return false (becomes zero), at this point,

the execution get out of the while loop• You can use the break statement to jump out of the loop• In general, frequent use of the break statement is bad

programming

Examples on while Statementint i = 0;

while (i < 9){

printf(“i = %d\n”, i);

i++;

}

char ch;

ch = getchar();

while (ch != EOF){

if (ch == ‘4’) break;

ch = getchar();

}

if (ch == ‘4’)

printf(“Bad number\n”);

else

printf(“Good number\n”);

Beware of infinite loops!!!

Loops---for statement• Statement structurefor (expr1; expr2; expr3)

statements

equivalent toexpr1;

while (expr2){

statements

expr3;

}

• expr2 is evaluated

• If expr2 is true, the statements and expr3 are executed and expr2 is re-evaluated

• Until expr2 becomes false, then the execution will jump out of the for loop

• You can use the break statement to jump out of the loop

• Using a break statement to jump out from a for loop is a very bad practice in programming!

Examples on for statementint i; int i;

i = 0; for (i = 0; i < 9; i++)

while (i < 9){ printf(“i = %d\n”, i);

printf(“i = %d\n”, i);

i++;

}

• The for statement’s structure can be viewed as:for (initialize-loop-index; condition; incremental-steps)

statement-body

• initialize-loop-index and incremental-steps are usually assignments or function calls

• condition is usually a relational expression

• Any of the three parts can be omitted, but the semi-colons must remain

• If expr2 (condition) is omitted, it is permanently true

• The code for (; ; ){ ...} refers to an infinite loop! You will need a break statement to get out of it

Loops---do while statement• Statement structuredo

statements

while (expression);

• The do while statement is almost like a while statement

• while the while and for loops test the termination condition at the top, the do while statement test the condition at the bottom after executing the statements at least once

• Two examples: keeping track of the number of char being readint n; int n;

char ch; char ch;

n = 0; n = 0;

while ((ch = getchar()) != ‘ ‘){ do{

n++; ch = getchar();

} n++;

}while (ch != ‘ ‘);

Nested Loops• Nested loops means loops inside a loopint i, j; int i, j;

for (i = 1; i < 10; i++){ i = 1;

printf(“%3d”, i); while (i < 10){

for (j = 1; j < 10; j++){ printf(“%3d”, i);

printf(“%3d”, i*j); j = 1;

} while (j < 10){

printf(“\n”); printf(“%3d”,i*j);

} j++;

}

printf(“\n”);

i++;

}

• Program output: 1 1 2 3 4 5 6 7 8 9

2 2 4 6 8 10 12 14 16 18

3 3 6 9 12 15 18 21 24 27

4 8 12 ....................

#include <stdio.h>main(){ int count = 0; int overall = 0; int i, j, k, n; n = 7; for (i = 1; i <= 6; i++) for (j = 1; j <= 6; j++) for (k = 1; k <= 6; k++){ if (i + j + k == n){ count++; printf("%3d%3d%3d\n", i, j, k); } overall++; } printf("\nCount: %d", count); printf("\nPercentage: %f%%\n", count * 100.0 / overall);}

1 1 5 1 2 4 1 3 3 1 4 2 1 5 1 2 1 4 2 2 3 2 3 2 2 4 1 3 1 3 3 2 2 3 3 1 4 1 2 4 2 1 5 1 1

Count: 15Percentage: 6.944444%

A program called “dice.c”

A Word on the break Statement• The break statement provides an early exit from for, while ,

do-while and switch statements

• A break causes the innermost enclosing loop or switch to be exited immediately

Commands and Sections not recommended to be used

• The continue statement. (section 3.7) page 64-65– Not a natural way to test for a condition

• The goto and labels. (section 3.8) page 65-66– Produced spaghetti codes.

• The declaration int a[10] defines an array a of size 10

• a[10] represents a block of 10 consecutive object named : a[0], a[1], a[2], ... a[9]

a[0] a[1] a[2] .....

• a[10] declares a to be an array of 10 integers

• Array subscripts always starts at zero in C

• A subscript can be any integer expression, which includes integer variables like i, and integer constants

• The notation a[i] refers to the i-th element of the array

• Each element is to be treated as a variable of the defined type; a[i] is an integer variable

Arrays

A Program on Counting Digits#include <stdio.h>

main()

{

char c;

int i, num_digit[10];

for (i = 0; i < 10; i++)

num_digit[i] = 0;

while ((c = getchar()) != EOF){

switch (c){

case ‘0’: case ‘1’: case ‘2’: case ‘3’: case ‘4’:

case ‘5’: case ‘6’: case ‘7’: case ‘8’: case ‘9’:

num_digit[c - ‘0’]++;

break;

default : break;

}

}

printf(“Distribution among the digits: \n”);

for (i = 0; i < 10; i++)

printf(“num_digit[%d] = %3d\n”, i, num_digit[i]);

}

A program on Binary Search#include <stdio.h>

main()

{

int x, n, a[100], low, high, mid, found;

/* find x in array a; a[0]<=a[1]<=...<=a[99];

assume we filled array a with values */

n = 100; /* number of elements */

x = 37; /* the number to be found */

low = 0;

high = n - 1;

found = 0;

while ((low <= high) && (!found)){ while (low <= high){

mid = (low+high) / 2; mid = (low+high) / 2;

if ( x < a[mid]) if (x < a[mid])

high = mid -1; high = mid - 1;

else if (x > a[mid]) else if (x > a[mid])

low = mid + 1; low = mid + 1;

else else{

found = 1; found = 1;

} break;

} if (found) printf(“a[%2d] = %d\n”, mid, a[mid]); }

else printf(“No element in a contains the value of %d\n”, x);

}

• The declaration int A[5][20]; declares a two-dimensional array A with 5 rows by 20 columns

• The variable A[x][y] represents the element in the x-th row and y-th column in the array A

• Two-dimensional arrays can represents:– Your appointment schedule --- int schedule[24][7];– Two-dimensional matrix --- int matrix_A[3][3];

• When you declare an array, like a variable, you have to initialize it

• You cannot assume any value when you declare an array, you have to initialize it.

int a[100], i;

for (i = 0; i < 100; i++) a[i] = 0;

• You can define the array of any type, not just integer, but floating point or character or others

• An array of char is also called string

Multi-dimensional Arrays