COM 121 Lecture Note
COM 121 Lecture Note
A programming language is an artificial language that can be used to control the behaviour of a machine,
particularly a computer. Programming languages, like human languages, are defined through the use
of syntactic and semantic rules, to determine structure and meaning respectively.
Programming languages are used to facilitate communication about the task of organizing and manipulating
information, and to express algorithms precisely. Some authors restrict the term "programming language" to
those languages that can express all possible algorithms; sometimes the term " computer language" is used for
more limited artificial languages.
• Later, with the advent of terminals with keyboards and monitors, such programs
were written as sequences of hexadecimal numbers, where each hexadecimal
digit represents a four binary digit sequence
• Furthermore, since each processor provides its own assembler dialect, assembly
language programs tend to be non-portable; a program must be rewritten to run
on a different machine.
• The 1950s and 60s saw the introduction of high-level languages, such as Fortran
and Algol.
Program Structure
A C program basically consists of the following parts:
Preprocessor Commands
Functions
Variables
Statements & Expressions
Comments
Let us look at a simple code that would print the words "Hello World":
#include <stdio.h>
int main()
{
/* my first program in C */
printf("Hello, World! \n");
return 0;
}
The first line of the program #include <stdio.h> is a preprocessor
command, which tells a C compiler to include stdio.h file before going to
actual compilation.
The next line int main() is the main function where the program execution
begins.
The next line /*...*/ will be ignored by the compiler and it has been put to add
additional comments in the program. So such lines are called comments in
the program.
The next line printf(...) is another function available in C which causes the
message "Hello, World!" to be displayed on the screen.
The next line return 0; terminates the main() function and returns the value
0.
Understanding the Basic Syntax of C programming
Tokens
A C program consists of various tokens and a token is either a keyword, an
identifier, a constant, a string literal, or a symbol. For example, the following C
statement consists of five tokens:
Semicolons
The semicolon is a statement terminator. That is, each individual
statement must be ended with a semicolon. It indicates the end of one logical
entity. For example, below are two different statements;
1. printf("Hello, World! \n");
2. return 0;
Comments
Comments are like helping text in your C program and they are ignored by the
compiler. They start with /* and terminate with the characters */
Benefits of using comments in C
• To explain and show program author, modification changes,
revisions, etc.
• To document variables/functions and uses or reason for their
usage.
• To aid understanding of difficult portions of a program.
• It reveals programmer’s prowess and expertise because comments
are written as coding is done.
Header Files
They are importable external functions and variables to C programs
similar to a library. Header files enable preprocessor perform tasks
such as printing, strings handling, maths, reading of variables etc. It is of
the form: #include <stdio.h>, #include <math.h>, #include “mylib.h”,
#include<string.h> usually placed at beginning of C source files.
• <> in the header file for directory search of information to compiler
• “ “ to search current directory of file name e.g. mylib.h
Keywords
• Keywords are reserved and must not be used as identifier names, constants
or variables totaling 29. Some common C keywords are auto, else, long,
break, enum, register, while, typedef, union, char, float, for, void, goto,
signed, etc.
Functions
• A function contains statements that specify the computing operations to be
carried out.
A function is a group of statements that together perform a task. Every C program
has at least one function, which is main(), and all the most trivial programs can
define additional functions.
You can divide up your code into separate functions. How you divide up your code
among different functions is up to you, but logically the division is such that each
function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function.
Variables
Variable is nothing but a name given to a storage area that our programs can
manipulate. Variables store values used during the computation. Each variable in C
has a specific type, which determines the size and layout of the variable's memory;
the range of values that can be stored within that memory; and the set of
operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and lowercase
letters are distinct because C is case-sensitive.
Data type
• It is a way or style of declaring variables or functions of diverse kinds.
• It determine the storage space allocation
• It interprets bit stored in an appropriately manner.
• Basic type: arithmetic = integer and floating- point
• Enumerated types: Assign only discrete (individually separated) integer
values.
• Type Void: no value is available or null value
• Derived or aggregate type: pointer, array, structure, union and function
types.
Basic Data Types
• Floating point is a number containing fractional parts or decimal points -
negative/positive e.g. 1.76e5 (i.e. 1.76x10 5), 3.122e2, etc.
• Format: float var; e.g. float sum;
• Double has higher precision than float variable e.g. double voltage;
• Character are single letters or number or symbol e.g. char letter;
Use single quote to assign character values.
Symbolic Constants
Constants are values assigned to names that cannot be altered.
There are two simple ways in C to define constants:
Using #define preprocessor. E.g. #define LENGTH 10
Using const keyword. E.g. const int LENGTH = 10;
• #define is used to declare them without delimiters (;)
• Usually coded in UPPERCASE (but, not a rule)
• Do not assign values to symbolic constants.
Examples of symbolic constant:
i. #define N 3000
ii. # define FALSE 0
iii. #define PI 3.142
iv. #define Figure “triangle”
Note
1. Variables are case sensitive::::::: Sum is not the same as sum…
2. Declare format: data_type var, var, …;
e.g. int I, j , k; float length, height; char midnit;
Storage classes
A storage class defines the scope (visibility) and life-time of variables and/or
functions within a C Program. They precede the type that they modify. We have
four different storage classes in a C program:
auto
register
static
extern
Operators
An operator is a symbol that tells the compiler to perform specific mathematical or
logical functions. C language is rich in built-in operators and provides the following
types of operators:
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
Arithmetic Operators
The following are all the arithmetic operators supported by the C language. Assume
variable A holds 10 and variable B holds 20, then:
+ Adds two operands. A + B = 30
- Subtracts second operand from the first. A - B = -10
* Multiplies both operands. A * B = 200
/ Divides numerator by de-numerator. B / A = 2
% Modulus Operator and remainder of after an integer division. B % A = 0
++ Increment operator increases the integer value by one. A++ = 11
-- Decrement operator decreases the integer value by one. A-- = 9
Relational Operators
The following table are the relational operators supported by C. Assume variable A
holds 10 and variable B holds 20, then:
== Checks if the values of two operands are equal or not. If yes, then the condition
becomes true.
(A == B) is not true.
!= Checks if the values of two operands are equal or not. If the values are not
equal, then the condition becomes true. (A != B) is true.
> Checks if the value of left operand is greater than the value of right operand.
If yes, then the condition becomes true. (A == Checks if the values of two operands
are equal or not. If yes, then the condition becomes true. (A == B) is not true.
!= Checks if the values of two operands are equal or not. If the values are not
equal, then the condition becomes true. (A != B) is true.
> Checks if the value of left operand is greater than the value of right operand.
If yes, then the condition becomes true.
(A > B) is not true.
< Checks if the value of left operand is less than the value of right operand. If
yes, then the condition becomes true. (A < B) is true.
>= Checks if the value of left operand is greater than or equal to the value of
right operand. If yes, then the condition becomes true. (A >= B) is not true.
<= Checks if the value of left operand is less than or equal to the value of right
operand. If yes, then the condition becomes true. (A <= B) is true. B) is not true.
< Checks if the value of left operand is less than the value of right operand. If
yes, then the condition becomes true. (A < B) is true.
>= Checks if the value of left operand is greater than or equal to the value of
right operand. If yes, then the condition becomes true. (A >= B) is not true.
<= Checks if the value of left operand is less than or equal to the value of right
operand. If yes, then the condition becomes true. (A <= B) is true.
Output
Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or equal to b
Line 5 - b is either greater than or equal to b
Logical Operators
Below are all the logical operators supported by C language. Assume variable A
holds 1 and variable B holds 0, then:
&& Called Logical AND operator. If both the operands are non-zero, then the
condition becomes true. (A && B) is false.
|| Called Logical OR Operator. If any of the two operands is non-zero, then the
condition becomes true. (A || B) is true.
! Called Logical NOT Operator. It is used to reverse the logical state of its
operand. If a condition is true, then Logical NOT operator will make it false. !(A &&
B) is true.
The example below shows the use of logical
operators:
#include <stdio.h>
main()
{
int a = 5;
int b = 20;
int c ;
if ( a && b )
{
printf("Line 1 - Condition is true\n" );
}
if ( a || b )
{
printf("Line 2 - Condition is true\n" );
}
/* lets change the value of a and b */
a = 0;
b = 10;
if ( a && b )
{
printf("Line 3 - Condition is true\n" );
}
else
{
printf("Line 3 - Condition is not true\n" );
}
if ( !(a && b) )
{
printf("Line 4 - Condition is true\n" );
}
}
Output
Line 1 - Condition is true
Line 2 - Condition is true
Line 3 - Condition is not true
Line 4 - Condition is true
Assignment Operators
The following tables lists the assignment operators supported by the C language:
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression and
decides how an expression is evaluated. Certain operators have higher precedence
than others; for example, the multiplication operator has a higher precedence than
the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a
higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Example:
#include <stdio.h>
main()
{
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
printf("Value of (a + b) * c / d is : %d\n", e );
e = ((a + b) * c) / d; // (30 * 15 ) / 5
printf("Value of ((a + b) * c) / d is : %d\n" , e );
e = (a + b) * (c / d); // (30) * (15/5)
printf("Value of (a + b) * (c / d) is : %d\n", e );
e = a + (b * c) / d; // 20 + (150/5)
printf("Value of a + (b * c) / d is : %d\n" , e );
return 0;
}
Output
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50