0% found this document useful (0 votes)
9 views

COM 121 Lecture Note

Uploaded by

Dan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

COM 121 Lecture Note

Uploaded by

Dan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

COM 121

PROGRAMMING USING C LANGUAGE


Concept of programming language
A programming language is a vocabulary and set of grammatical rules for instructing
a computer or computing device to perform specific tasks. The term programming
language usually refers to high-level languages, such as BASIC, C, C+
+, COBOL, Java, FORTRAN, Ada, Pascal, Python, Javascript, Ruby, SQL, Swift, Perl, etc.

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.

How programming languages work


Each programming language has a unique set of keywords (words that it understands)
and a special syntax for organizing program instructions.

• The native language of a computer is binary—zero and ones—and all instructions


and data must be provided to it in this form.

• Native binary code is called machine language.

• The earliest digital electronic computers were programmed directly in binary,


typically via punched cards, plug-boards,or front-panel switches

• 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

• Developing correct programs in machine language is tedious and complex, and


practical only for very small programs.

• In order to express operations more abstractly, assembly languages were


developed.

• These languages have simple mnemonic instructions that directly map to a


sequence of machine language operations.
• Examples

• the MOV instruction moves data into a register

• the ADD instruction adds the contents of two registers together.

• Programs written in assembly language are translated to machine code using an


assembler program.

• While assembly languages are a considerable improvement on raw binary, they


still very low-level and unsuited to large-scale programming

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

• HLL languages provide subroutines and conditional looping constructs, which


greatly enhance the structure of a program, making it easier to express the
progression of instruction execution; that is, easier to visualize program flow.

• These are called an abstraction of the underlying machine instructions and,


unlike assembler, are not tied to any particular hardware.

• A program written in a HLL can be transferred or ported to a another machine


and run without change.

• HLL languages provide subroutines and conditional looping constructs, which


greatly enhance the structure of a program, making it easier to express the
progression of instruction execution; that is, easier to visualize program flow.

• These are called an abstraction of the underlying machine instructions and,


unlike assembler, are not tied to any particular hardware.

• A program written in a HLL can be transferred or ported to another machine and


run without change.

• To produce executable code from such a program, it is translated to machine


specific assembler language by a compiler program.

• Thereafter, it is converted to machine code by an assembler.


Program
A program is a set of instructions that a computer uses to perform a specific function.
The C programming language

C is a general-purpose high-level language that was originally developed by


Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was
originally first implemented on the DEC PDP-11 computer in 1972. In 1978,
Brian Kernighan and Dennis Ritchie produced the first publicly available
description of C, now known as the K&R standard. The UNIX operating
system, the C compiler, and essentially all UNIX application programs have
been written in C.
All C programs are usually named with extension “.c” e.g. com121.c

Reasons for C language?


• Easy to learn
• Structured language
• It produces efficient programs
• It can handle low-level activities
• It can be compiled on a variety of computer platforms
• Popularly referred to as mid-level language
It is also efficient in building the following programs:
• Assemblers
• Text Editors
• Print Spoolers
• Network Drivers
• Modern Programs
• Databases
• Language Interpreters
• Utilities
Local Environment setup and installation procedure

To install GCC on Windows, you need to install MinGW. To install MinGW, go to


the MinGW homepage, www.mingw.org, and follow the link to the MinGW
download page. Download the latest version of the MinGW installation program,
which should be named MinGW-<version>.exe.
While installing MinGW, at a minimum, you must install gcc-core, gcc-g++,
binutils, and the MinGW runtime, but you may wish to install more.
Add the bin subdirectory of your MinGW installation to your PATH environment
variable, so that you can specify these tools on the command line by their simple
names.
After the installation is complete, you will be able to run gcc, g++, ar, ranlib,
dlltool, and several other GNU tools from the Windows command line.

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:

printf("Hello, World! \n");


The tokens are;
1. Printf
2. (
3. "Hello, World! \n"
4. )
5. ;

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.

Some terms in C programming


Expression combines constants, variables operators and function calls e.g.
a+b
3.4*x – 12.45
t an(angle)
Statement is an expression delimited with a semicolon(;) e.g.
sum = g + h + j;
printf(“Go Manager!”);
area = PI*R*R;
Assignment operator uses equal sign (=) to give value to variable of an
expression e.g. i=0; x=34.9; sum=a+b; midnit = ‘J’; j =j+3;

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”

The example below depicts constants and variables in a C program

/*This is a C program to calculate the area of circle */


#include <stdio.h>
#define R 2
#define PI 3.142
int main ()
{
float area;
area = PI * R * R;
printf("The area of the circle is %.2f\n", area);
return 0;
}

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;

Initializing variables similar to constants


#include <stdio.h>
main()
{
int distance=33;
float time=10.7;
char school;
double speed;
school='S'; /* assign character value similar to acronym*/
speed=distance*time;
printf("value of time taken is %f\n",time);
printf("value of distance taken is %d\n",distance);
printf("value of speed of car is %.4f\n",speed);
printf("value of school is %c\n",school);
}

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

The example below shows the use of arithmetic


operators:
#include <stdio.h>
main()
{
int a = 21;
int b = 10;
int c ;
c = a + b;
printf("Line 1 - Value of c is %d\n", c );
c = a - b;
printf("Line 2 - Value of c is %d\n", c );
c = a * b;
printf("Line 3 - Value of c is %d\n", c );
c = a / b;
printf("Line 4 - Value of c is %d\n", c );
c = a % b;
printf("Line 5 - Value of c is %d\n", c );
c = a++;
printf("Line 6 - Value of c is %d\n", c );
c = a--;
printf("Line 7 - Value of c is %d\n", c );
}
Output
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 21
Line 7 - Value of c is 22

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.

The example below shows the use of relational


operators:
#include <stdio.h>
main()
{
int a = 21;
int b = 10;
int c ;
if( a == b )
{
printf("Line 1 - a is equal to b\n" );
}
else
{
printf("Line 1 - a is not equal to b\n" );
}
if ( a < b )
{
printf("Line 2 - a is less than b\n" );
}
else
{
printf("Line 2 - a is not less than b\n" );
}
if ( a > b )
{
printf("Line 3 - a is greater than b\n" );
}
else
{
printf("Line 3 - a is not greater than b\n" );
}
/* Lets change value of a and b */
a = 5;
b = 20;
if ( a <= b )
{
printf("Line 4 - a is either less than or equal to b\n" );
}
if ( b >= a )
{
printf("Line 5 - b is either greater than or equal to b\n" );
}
}

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:

The example below shows the use of assignment


operators:
#include <stdio.h>
main()
{
int a = 21;
int c ;
c = a;
printf("Line 1 - = Operator Example, Value of c = %d\n",
c );
c += a;
printf("Line 2 - += Operator Example, Value of c = %d\n", c
);
c -= a;
printf("Line 3 - -= Operator Example, Value of c = %d\n", c
);
c *= a;
printf("Line 4 - *= Operator Example, Value of c = %d\n", c
);
c /= a;
printf("Line 5 - /= Operator Example, Value of c = %d\n", c
);
c = 200;
c %= a;
printf("Line 6 - %= Operator Example, Value of c = %d\n", c
);
}
Output
Line 1: = Operator Example, Value of c = 21
Line 2: += Operator Example, Value of c = 42
Line 3: -= Operator Example, Value of c = 21
Line 4: *= Operator Example, Value of c = 441
Line 5: /= Operator Example, Value of c = 21
Line 6: %= Operator Example, Value of c = 11

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

You might also like