Basic Programming Handouts
Basic Programming Handouts
Handout #2
PRELIMINARIES
Example 1:
void main(void)
{
printf(“Hello\n”);
}
The program shown in the example above is what is referred to as a program source code. The source code is made
up of a combination of letters, numbers and other symbols. The source code can be created by the programmer/user
using any text editor.
#include <stdio.h>
void main(void)
{
...your variable declarations...
...your statements...
}
What is a statement?
All C programs are made up of a sequence of instructions. In C, instructions are also called statements. In the
English language, a statement is terminated by a period, a question mark or an exclamation point.
Note that in C language, a statement is terminated by a semicolon. In the example program above, there is only one
statement -- the printf() statement.
What is a function?
All statements should be written inside a user-defined function. You may think of a function as a group or sequence
of statements. It is analogous to the English language wherein a paragraph is made up of a sequence of statements.
The word “user-defined” means that it is the user who defined (or wrote) the description of a function. In the example
program above, there is only one user-defined function – the main() function. All C programs must have a main()
function.
C Programming Handout #2: Naming, Types, Operators 2
The symbol { is referred to as open brace or open curly bracket. Likewise, the symbol } is called close brace or close
curly bracket. The curly brackets are used for grouping purposes. Think of a curly bracket as something
synonymous to begin and the close curly bracket as the symbol for end. Thus, in the example program above, the
open and close curly brackets designate the beginning and the end of the main() function respectively. Note that
the curly brackets must always come in pair. A missing curly bracket is one of the most common cause of syntax
errors.
The symbols /* and */ are used to group comments inside the program. Comments are not instructions, rather they
simply provide additional information (a textual description) such as what the program is doing, what are the inputs,
what are the outputs etc. Think of /* as the beginning of a comment, and the */ as the end a comment. Just like the
curly brackets, they symbols always come in pair. Comments are optional and maybe placed anywhere within the
program source code.
The meaning of the other symbols, i.e. #include<stdio.h> and void will be explained later.
C Programming Handout #2: Naming, Types, Operators 3
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]:
Examples:
a
A
main
void
hello
salary
rate_per_hour
student_1
student_2
student_3
First_Name
ComputeGrade
What is a keyword?
As a language, C has its own vocabulary – a set of keywords. These names are reserved and cannot be used for other
purposes such as in naming user-defined variables names. In the example program, the names void and main are
keywords.
The ANSI C language has 32 keywords (ONLY!). The complete list of C keywords are tabulated in [Kernighan &
Ritchie, p. 192].
Note that the name 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. The concept of a library will be explained in the latter part of
the course.
C Programming Handout #2: Naming, Types, Operators 4
What is a constant?
A constant is an entity whose value does not change. A constant can either be numeric constant or a literal constant.
Example:
1
500
-100.100
3.1416
‘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.
What is a variable?
A program is made of data and instructions to manipulate those data. Note that data have to be stored somewhere,
and thus will need some memory space in the RAM.
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
The concept of scope and lifetime will be discussed in the latter part of the course.
▪ char – the character data type. The char data type is used to represent/store/manipulate character data
values. A char data type 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.
▪ int – the integer data type. The int data type is used to represent/store/manipulate signed whole numeric
values.
▪ float – the single precision floating point data type. The float data type is used to store single precision
signed real numbers (i.e., those numbers with fractional components).
▪ double – the double precision floating point data type. The double data type is used to store double precision
signed real numbers.
The amount of memory space required to store an int, a float and double is machine-dependent. For 32-bit
machines, an int and float requires 4 bytes of memory each, while 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.
How can you determine the actual size of each data type?
The following program can be used to print the sizes of the basic data types:
#include <stdio.h>
void main(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));
}
The sizeof() is a predefined library function that yields the size in number of bytes of the specified data type.
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;
C Programming Handout #2: Naming, Types, Operators 6
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, variables must be
separated by a comma. A missing comma will generate a syntax error.
Example:
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 x1. 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:
OPERATORS
C Programming Handout #2: Naming, Types, Operators 7
Operators are symbols representing operations that can be performed on constants and variables.
▪ Assignment Operation
▪ Arithmetic Operation
▪ Relational Operation
▪ Logical Operation
The assignment operator is denoted by the equal symbol, i.e. =. It is used to store (i.e., assign) a value to a variable.
The syntax of an assignment operation is:
The assignment operation is also called an assignment statement; thus it should be terminated by a semicolon.
Example:
Note that it is possible to assign a value of a variable to another variable of a compatible data type:
Example:
ch1 = ‘Z’;
ch2 = ch1;
x = 5;
y = x;
z = x;
The question in general is, what will happen if I assigned a value whose data type is different from the data type of the
receiving variable?
The answer is, 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.
The precise rules of conversions are described in [Kernighan & Ritchie, p. 197].
The basic arithmetic operations, plus some other operations are available in C language. These are as follows:
▪ + denotes addition
▪ - denotes subtraction
▪ * denotes multiplication
▪ / denotes division
▪ % denotes modulus operator (yields the remainder)
The +, -, *, / can be used for operands of type int, float and double data types. The % operator can be
used only with integer operands. All of these operators are called binary operators because they require two
operands.
Example:
The following program shows how to use the arithmetic operators with integer operands:
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;
Example:
The following program shows how to use the operators with real numbers as operands:
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);
}
A sequence of arithmetic operations is evaluated following the MDAS rule, i.e., multiplication and division should be
performed first before addition and subtraction.
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 can use any constant value for initialization purposes.
1. 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.
▪ == denotes equal to
▪ != denotes not equal to
▪ > denotes greater than
▪ < denotes less than
▪ >= denotes greater than or equal to
▪ <= denotes less than or equal to
The relational operators can be performed on all the basic data types. Relational operation should be enclosed in a
pair of parentheses.
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.
It is important to note that 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.
Example:
#include <stdio.h>
void main(void)
{
int a, b, c, d, e, f;
int x, y;
x = 5;
y = 10;
a = (x == y);
b = (x != y);
c = (x > y);
d = (x < y);
e = (x >= y);
f = (x <= y);
Exercises:
The logical operators are normally used in conjunction with relational operators to test for multiple conditions.
Note that the 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 should be performed before logical AND before logical OR.
!0 results in 1
!1 results in 0
0 && 0 results in 0
0 && 1 results in 0
1 && 0 results in 0
1 && 1 results in 1
For you to easily memorize the result, just remember that in a logical AND operation all operands must be 1 to have a
result of 1.
0 || 0 results in 0
0 || 1 results in 1
1 || 0 results in 1
1 || 1 results in 1
For you to easily memorize the result, just remember that in a logical OR operation if at least one of the operand is 1,
the result will be 1.
Example:
An actual C program that shows the result of the operators is included below.
#include <stdio.h>
void main(void)
{
int a, b;
/* logical or operator */
printf(“0 || 0 = %d\n”, 0 || 0);
printf(“0 || 1 = %d\n”, 0 || 1);
printf(“1 || 0 = %d\n”, 1 || 0);
printf(“1 || 1 = %d\n”, 1 || 1);
}
The order of evaluation of operators depends on their precedence (sometimes called priority). The precedence rules
are as follows: