0% found this document useful (0 votes)
17 views13 pages

Basic Programming Handouts

This document discusses key concepts in C programming including: 1) A C program consists of statements grouped into functions with main() being required. Statements end with semicolons while functions are delimited by curly braces. 2) Variables store and represent data in memory and must be declared with a data type like int, float, char etc. Constants cannot change value once declared. 3) Comments are for documentation and begin/end with /* */ while names follow conventions like starting with a letter and avoiding keywords.

Uploaded by

Nympha Lachaona
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
17 views13 pages

Basic Programming Handouts

This document discusses key concepts in C programming including: 1) A C program consists of statements grouped into functions with main() being required. Statements end with semicolons while functions are delimited by curly braces. 2) Variables store and represent data in memory and must be declared with a data type like int, float, char etc. Constants cannot change value once declared. 3) Comments are for documentation and begin/end with /* */ while names follow conventions like starting with a letter and avoiding keywords.

Uploaded by

Nympha Lachaona
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 13

C Programming Handout #2: Naming, Types, Operators 1

Handout #2

Preliminaries, Naming, Types, Operators

PRELIMINARIES

How does a typical C program look like?

First, a very simple example of a C program:

Example 1:

/* Sample C program that outputs the word “Hello” */


#include <stdio.h>

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.

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

#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

What is the use of { } symbols?

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.

What is the use of /* */ symbols?

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

What is a name? What are the naming conventions in C?

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]:

1. Names are made up of letters and digits.


2. The first character must be a letter.
3. C is case-sensitive, i.e., 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:

The following are examples of valid names:

a
A
main
void
hello
salary
rate_per_hour
student_1
student_2
student_3
First_Name
ComputeGrade

The following are examples of invalid names:

1 /* must start with a character */


1_ab /* must start with a character */
a& /* & symbol cannot be used in a name */
xyz_% /* % cannot be used in a name */
$money /* must start with a character,
$ cannot be used in a name */

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

CONSTANTS, VARIABLES, DATA TYPES, DECLARATIONS

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:

Example of numeric constants

1
500
-100.100
3.1416

Example 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.

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

▪ 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
▪ a lifetime

The concept of scope and lifetime will be discussed in the latter part of the course.

What is a data type?

A data type specifies

▪ the kind of values 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

What (basic) data types are available in C language?


C Programming Handout #2: Naming, Types, Operators 5

There are four basic data types, namely:

▪ 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.

What is variable declaration?

A variable declaration is an “action” by which a variable is “introduced” to a program/function. All variables in a C


program must be declared. If you forgot to do so, the compiler will report a syntax error.

How do you declare a variable?

In C, the 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;
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:

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 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.

What is the value of the variable initially?

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
C Programming Handout #2: Naming, Types, Operators 7

What are operators?

Operators are symbols representing operations that can be performed on constants and variables.

What are the basic operations available in C language?

▪ Assignment Operation
▪ Arithmetic Operation
▪ Relational Operation
▪ Logical Operation

How do you perform an assignment operation in C?

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:

<variable name> = <expression>

The assignment operation is also called an assignment statement; thus it should be terminated by a semicolon.

Example:

/* sample program demonstrating the use of assignment statement */


#include <stdio.h>
void main(void)
{
char ch;
int i;
float f;
double d;

ch = ‘A’; /* assign a char value to char variable */


i = 5; /* assign an int value to int variable */
f = 1.25; /* assign a float value to float variable */
d = 3.14159; /* assign a double value to double variable */
}

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;

What will happen if I assigned a double to an int?


C Programming Handout #2: Naming, Types, Operators 8

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 basic rules of data type conversion are as follows:

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


int/float/double value.
2. 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
3. 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
4. int to float/double assignment: the int value will be converted automatically to float/double value
5. 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
6. float to double assignment: the floating point value will be converted automatically to double data type
7. 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

The precise rules of conversions are described in [Kernighan & Ritchie, p. 197].

How do you perform arithmetic operations in C?

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:

/* Sample program illustrating how to use arithmetic operators */


#include <stdio.h>
C Programming Handout #2: Naming, Types, Operators 9

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);
}

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);
}

What about the 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.


C Programming Handout #2: Naming, Types, Operators 10

Example:

Given the expression:

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.

How do you perform relational operations in C?


C Programming Handout #2: Naming, Types, Operators 11

The relational operators in C are as follows:

▪ == 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);

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);
}

Exercises:

What is the result of the following relational operations?

1. (‘A’ > ‘B’) 4. (5.0 <= 10.0/2.0) 7. (‘y’ == ‘Y’)


2. (123 == 321) 5. (3 + 5 * 10 != 3 * 5 + 10)
3. (1+2+3 >= 3+2+1) 6. (‘A’ == 65)
How do you perform logical operations?

The logical operators in C are as follows:


C Programming Handout #2: Naming, Types, Operators 12

▪ ! denotes logical NOT


▪ && denotes logical AND
▪ || denotes logical OR

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.

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

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.

The semantics of the || operator is as follows:

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 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(“1 && 0 = %d\n”, 1 && 0);
printf(“1 && 1 = %d\n”, 1 && 1);
C Programming Handout #2: Naming, Types, Operators 13

/* 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);
}

What is the precedence/order of evaluation of operators?

The order of evaluation of operators depends on their precedence (sometimes called priority). The precedence rules
are as follows:

▪ The arithmetic operators should be performed before relational operations.


▪ Relational operations should be performed before logical operations.
▪ Within arithmetic operations, follow the MDAS rule.
▪ Within the logical operators, logical NOT should be performed before logical AND. Logical AND should be
performed before logical OR.
▪ Operators of the same precedence should are usually evaluated from left going to the right.
▪ A pair of parentheses will override the usual priority.

You might also like