You are on page 1of 63

PRELIMINARIES, NAMING, TYPES, OPERATORS

Typical C program
/* Sample program that outputs the word Hello*/ #include <stdio.h> void main (void) { printf (Hello\n); }

program source code made up of combinations of letters, numbers and other symbols can be created using a text editor

In class, we will write C programs using the following format:


#include <stdio.h>

void main (void) { your variable declarations your statements


}

Statements instructions - terminated by a semicolon Function a group or sequence of statements


All statements should be written inside a userdefined function All C programs must have a main( ) function

the use of { } symbols


used for grouping purposes synonymous to begin and end must always come in pair A missing brace/curly bracket is one of the most common syntax errors

the use of / * * / symbols


used to group comments inside the program Comments are not instructions but provide additional information (textual description) such as what the program is doing, what the inputs and outputs are, etc
/ * beginning of a comment * / the end a comment always come in pairs Comments are optional and maybe placed anywhere within the program source code.

It is possible to write several lines of comments inside / * * /

comments cannot be nested, i.e. you cannot put / * * / inside / * * /.

NAMING CONVENTIONS
Data and instructions to manipulate data are referred to by their names. In C, there are rules and conventions to follow in giving a name to something; these are as follows [Kernighan & Ritchie, p. 35]:

NAMING CONVENTIONS
1. Names are made up of letters and digits. 2. The first character must be a letter. 3. C is case-sensitive, ie., the lower-case letter 'a' is not the same as the 'uppercase letter 'A'. 4. The underscore symbol_ is considered as a letter in C. It is not recommended to be used, however, as the first character in a name. 5. At least the first 31 characters of a name are significant.

examples of valid names: a A main void hello salary rate-per_hour student_l student_2 student_3 First_Name ComputeGrade

The following are examples of invalid names: 1 1_ab a& */ xyz_% $money /* must start with a character */ /* must start with a character */ /* & symbol cannot be used in a name /* % cannot be used in a name */ /* must start with a character, $ cannot be used in a name */

keywords
reserved names cannot be used for other purposes such as in naming user-defined variables names e.g. void The ANSI C language has 32 keywords (ONLY!). The complete list of C keywords are tabulated in [Kernighan & Ritchie, p. 192].

printf is actually not a C keyword and is not really part of the C language. However, it is a name pre-defined in the standard input/output library

CONSTANTS. VARIABLES. DATA TYPES. DECLARATIONS


constant - an entity whose value does not change can either be numeric or literal Example:
numeric constants
1 500 -10000.100 3.1416

Examples of literal constants: 'A' "Hello" "The quick brown fox jumped over the lazy dog." Note: In C, a literal constant with only one character is referred to simply as a character. It is written such that it is enclosed in a pair of single quotes. If there is more than one character, it is called a string. A string is written enclosed in a pair of double quotes.

A variable is an entity that is used to store data. Without variables, there is no way (or actually NO PLACE) to store data. A variable has a name (more specifically a symbolic name) an associated physical memory space (portion in a RAM) a data type a value (depends on data type) a scope (will be discussed later) a lifetime (will be discussed later)

Data type
specifies
the kind of values that can be assumed by a variable of that type the range of values that can be assumed by a variable of that type the amount of memory (in bytes) needed by a variable to store a value of that type

(basic) data types


char - the character data type used to represent/store/manipulate character data values value requires one byte of memory space The range of values that can be assumed by a char value is from 0 to 255. The number-to-character coding that is used is ASCII.

(basic) data types


int - the integer data type used to represent/store/manipulate signed whole numeric values

(basic) data types


float - the single precision floating point data type used to store single precision signed real numbers (i.e., those numbers with fractional components) double - the double precision floating point data type used to store double precision signed real numbers

(basic) data types


The amount of memory space required to store an int, a float and double is platform-dependent. (depends on the machine and the software). For 32-bit machines (and 32-bit compilers such as Microsoft C compiler), an int and float requires 4 bytes of memory each. A double requires 8 bytes of memory Note that a char data is actually numeric (from 0 to 255), and is treated as a subset of int values. Any operation (discussed later) on integer values can also be performed on characters.

The following program can be used to print the sizes of the basic data types: #include <stdio.h> void rnain(void) { printf(Size of char: %d\n", sizeof(char)); printf(Size of int: %d\n", sizeof(int)); printf(Size of float: %d\n", sizeof(float)); printf(Size of double: %d\n", sizeof(double)); }

variable declaration - an "action" by which a variable is "introduced" to a program/function. All variables in a C program must be declared. If you forget to do so, the compiler will report a syntax error.

syntax for declaring a variable is as follows: <data type> <variable name> The symbol < item> means that is required to specify the item enclosed within a pair of angled brackets A semicolon signifies the end of a declaration. A missing semicolon will cause the compiler to generate a syntax error. Variables should be named following the C naming conventions.

Example: char ch; int i; float f; double d;

It is possible to declare several variables of the same type on the same line. In such a case, a comma should be inserted between two variables. A missing comma will generate a syntax error.

Example:
char ch1, ch2; int x, y, z; float hourly_rate, number_of_hours, salary; double numerator, denominator;

Can I use any name for the variables? YES, as long as you follow the naming conventions, and do not use the reserved words in C.

It is recommended, however, as a good programming practice for you to use a name that is descriptive or suggestive. For example, if you know that a variable will represent the hourly rate of a part-time worker, then don't use names such as xyz or xl. It is better to use a variable name such as rate or hourly_rate. Note that the use of the underscore makes reading the variable name easy to read.

By default, the value of a variable in C is GARBAGE, i.e., there is something stored in that memory space but that something is invalid for the intended use. A variable must be properly initialized. By initialize, we mean assigning a valid value to a variable. The use of a variable with a garbage value will cause a logical error - another type of error that is very difficult to find!

Exercises: 1. Declare middle initial as a character variable 2. Declare age as an integer variable 3. Declare deposit amount, withdrawal amount as a floating point variables 4. Declare length, width, height as double data type variables

OPERATORS
Operators - symbols representing operations that can be performed on constants and variables basic operations in C language
Assignment Operation Arithmetic Operation Relational Operation Logical Operation

Assignment Operator
denoted by the equal symbol, i.e. =. used to store (i.e., assign) a value to a variable syntax of an assignment operation: <variable name> = <expression> is also a statement and, therefore, should be terminated by a semicolon

/* sample program demonstrating the use of assignment statement */ #include <stdio.h> void main (void) { char ch; int i; float f; double d; ch = A'; i = 3; f = 2.75; d= 2.789468; } /* assign a char value to char variable*/ /* assign an int value to an int variable */ /* assign a float value to a float variable */ /*assign a double value to double variable*/

It is possible to assign a value of a variable to another variable of compatible data type. Example: ch1 = Z; ch2 = ch1; x = 7; y = x; z = x;

What will happen if I assign a value whose data type is different from the data type of the receiving variable? The data type will be converted (either demoted or promoted) In general, one that requires smaller memory will fit into one that requires big memory. The opposite will result into loss of information.

basic rules of data type conversion


char to int/float/double assignment: the char value will be converted automatically to an int/float/double value

Example: char ch; int i; float f; double d;


ch = ' A' ; i = ch; f = ch; d = ch;

/* value of i will be 65 (since 65 is the ASCII of 'A') */ /* value of f will be 65.000000 */ /* value of d will be 65.000000 */

basic rules of data type conversion


int to char assignment: if the int value is within the possible range of char values then that value is assigned; otherwise the behavior is undefined char ch; int i; i = 65; ch = i; i = 299; ch = i;

/* value of ch will be 65 or 'A' */

/* note that a char can only store up to 255, thus, this behavior is undefined */

basic rules of data type conversion


float/double to char assignment: the fractional part will be discarded; if the whole number is within the possible range of char values then that value is assigned; otherwise the behavior is undefined char ch; float f; double d; f = 65.123; ch = f;

/* value of ch will be 65 or 'A' */

d = 90.908765; ch = d; /* value of ch will be 90 or Z */ ch = 1000.89 /* behavior is undefined */

basic rules of data type conversion


int to float/double assignment: the int value will be converted automatically to float/double value int i; float f; double d; i = 123; f = i; d = i;

/* value of f will be 123.000000 */ /* value of d will be 123.000000 */

basic rules of data type conversion


float/double to int assignment: the fractional part will be discarded, the whole part will be assigned to the integer if and only if the whole part is within the range of possible int values; otherwise the behavior is undefined int i; float f; double d;

f = 135.66; i = f; d = -49.991234; i = d; i = 999999999999.99

/* value of i will be 135 */ /* value of I will be -49 */ /* very large number! behavior is undefined */

basic rules of data type conversion


float to double assignment: the floating point value will be converted automatically to double data type float f; double d; f = 8974.234; d = f;

/* value of d will be 8974.234 */

basic rules of data type conversion


double to float assignment: if the value is within the range of possible floating point values then a less precise value is assigned; otherwise, the behavior is undefined float f; double d; d = -875.39391234; f = d; /* value of f will be 875.393912 */ f = 9999999999999999.999 /* very large! behavior is undefined */

General rule: something that is small will fit into something that is big. The opposite does not hold true but will result into what is called as OVERFLOW.

Arithmetic Operations
+ denotes addition (yields the sum of two operands) - denotes subtraction (yields the difference of two operands) * denotes multiplication (yields the product of two operands) / denotes division (yields the quotiont of two operands) % denotes modulus operator (yields the remainder)

Arithmetic Operations
The +, -, *, / can be used for operands of type int, float and double data types. (Actually they can also be used on char since char is a subset of in t). The % operator can be used only with integer operands. All of these operators are called binary operators because they require two operands.

/* Sample program illustrating how to use arithmetic operators */ #include <stdio.h> void main(void) { int a, b, c, d, e, f; a = 5 + 10; b = 22 - 15; c = 2* 3; d = 20/8; e = 24 % 5; f = 5 % 10; printf("a = %d\n",a) ; printf("b = %d\n",b) ; printf("c = %d\n",c) ; printf("d = %d\n",d) ; printf("e = %d\n",e) ; printf("f = %d\n",f) ;

When the operands of the division operator are both whole numbers (i.e. char or integer values), the division results into an integer division. That is, it truncates the remainder of the division. example: 7/2 will not result to a 3 . 5 but rather 3 When one of the operands is a float or double, the division is a real number division. Thus:

7.0 / 2 will result to 3.5

/*The following program shows how to use the operators with real numbers as operands */ #include<stdio.h> void main(void) { float a,b; float x,y,z; a = 10.0; b = 25.0; x = a + b * 2.5; y = a * b + 2.5; z = a - b / 2.5; /* output results */ printf ("x = %f\n", x); printf ("y = %f\n", y); printf ("z= %f\n", z); }

Assigning a variable to a constant is an error (syntax error) 123 = a; /* ERROR! */

Assigning the value of a variable to a variable of the same name is syntactically correct, but IS USELESS AND ACTUALLY DOES NOT MAKE SENSE! a = 10; a = a;

/* logically useless; value of a is the same */

It is usual in programming to assign a value of an expression to a variable, wherein the old value of the variable is also used in the expression. example: a = 25; a = a + 1; /* old value of a is 25;added to 1 gives 26; thereafter,26 is assigned as the new value of a */ x = 20; x = x * 2; /* old value of x is 20;multiplied to 2 gives 40; thereafter,40 is assigned as the new value of x */

MDAS RULE
A sequence of arithmetic operations is evaluated following the MDAS rule, i.e., multiplication and division should be performed first before addition and subtraction. A pair of parentheses should be used to override the usual priority of operation. Example: A+B*C

Here the multiplication operation will be performed first before the addition. To perform the addition before multiplication, we have to write the arithmetic expression as: (A+B) *C

Exercises
Write a C program that will declare variables (using the appropriate data type) and assign values to these variables for the following problems. You may use any constant value for initialization purposes. I. The net income is computed as the gross income minus the income tax, SSS contribution and medical insurance. 2. The salary of a part time worker is computed as the product of the hourly rate and the number of hours worked. 3. The area of a rectangle is computed as length multiplied by width. 4. The circumference of the circle is computed as 2 multiplied by PI (a constant value approximated as 3.1416) multiplied by the radius. 5. Compute the sum of the integer values 1,3,5, 7, 8, and 9.

Relational Operations in C
The relational operators in C are as follows: == equal to != not equal to > greater than < less than >= greater than or equal to <= denotes less than or equal to

relational operators can be performed on all the basic data types In C, the result of a relational operation is either a 0 (zero) or a 1 (one). A zero means that the relation is FALSE and a one means that it is TRUE. The test for equality uses two equal symbols. Forgetting one of the equal sign is a very common logical (not syntactical) error - and this can be very difficult to debug in a fairly large program.

#include <stdio.h> void main(void) { int a, b, c, d, e, f, x, y; x = 5; y = 10; a =(x == y); b =(x!= y); c =(x > y); d =(x < y); e =(x >= y); f =(x <= y); printf("a = %d\n",a) ; printf("b = %d\n",b) ; printf("c = %d\n",c) ; printf("d = %d\n",d) ; printf("e = %d\n",e) ; printf("f = %d\n",f) ; }

The logical operators in C are as follows: ! denotes logical NOT && logical AND || logical OR The logical operators are normally used in conjunction with relational operators to test for multiple conditions. logical NOT is a unary operator, i.e., it is used only on one operand The remaining operators are binary operators (i.e., requires two operands). The logical NOT operation is performed before logical AND and before logical OR.

The semantics of the ! operator is as follows:

! 0 results in 1 ! 1 results in 0 The semantics of the && operator is as follows: 0 && 0 results in 0 0 && 1 results in 0 1 && 0 results in 0 1 && 1 results in 1

The semantics of the II operator is as follows: 0 II 0 0 II 1 1 II 0 1 II 1 results in 0 results in 1 results in 1 results in 1

/*An actual C program that shows the result of the operators */ #include <stdio.h> void main(void) { /* logical not operator */ printf("!0 = %d\n", !0); printf("!1 = %d\n", !1); /* logical and operator */ printf("0 && 0 = %d\n",0 && 0); printf("0 && 1 = %d\n",0 && 1); printf("l && 0 = %d\n",1 && 0); printf("l && 1 = %d\n",1 && 1);

/* logical or operator */ printf("0 || 0=%d\n", 0 || 0); printf("0 || 1=%d\n", 0 || 1); printf("l||0=%d\n", 1|| 0); printf("l || 1 = %d\n" , 1 || 1); }

++ used to increment (increase) the value of an integer variable by 1 -- used to decrement the value of an integer variable by one These operators are also applicable to character variables since characters are subsets of integers

char ch1, ch2; int i, j; i = 10; j= 5; i++; j--; ch1 ='A; ch2='Z' ; ch1++; ch2 -- ;

/* value of i becomes 11*/ /* value of j becomes 4*/ /* ch1 is also 65*/ /* ch2is also 90*/ /* value of ch1 becomes 66 or'B'*/ /* value of ch2 becomes 89 or'Y'*/

Precedence/order of evaluation
Operator Associativity ! ++ -- & sizeof Right to left * / % Left to right + Left to right < <= > >= Left to right == != Left to right && Left to right || Left to right = Right to left

Operators are listed in rows, with lower rows having lower precedence. Operators within the same row have the same precedence. For example, + and have the same precedence. Associativity specifies the order for multiple occurences of the same operator. a + b >= 3 * c == a != 2 * c + b 3 5 1 6 7 2 4

You might also like