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

Prepared By: Armilyn T. Martinez, Msit

Uploaded by

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

Prepared By: Armilyn T. Martinez, Msit

Uploaded by

Sonic Hedgehog
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Prepared by:

ARMILYN T. MARTINEZ, MSIT

This module or any portion thereof may not be reproduced or used in any manner whatsoever without
the written permission of the AUTHOR except for educational purposes but with a citation to this
source.

For Permission : Contact Bataan Heroes College, Roman Super Hi-way, Balanga City, Bataan,
Philippines
2 [COMPUTER PROGRAMMING 1 MODULE]

Course Information
Course Title: COMPUTER PROGRAMMING 1

Program: Electrical Engineering

Course Code: Comp 1 || EE 3A

Class Schedule : TThS 1:00PM – 2:50 PM

Online Meeting Schedule : Thursday 1:00PM – 2:50PM

Google Classroom Code: 7pcxyc3


Google Meet Link: https://meet.google.com/lookup/fqe37lv3k2?authuser=0&hs=179

Instructor Information
Name: Prof. Armilyn T. Martinez

Contact Information : Email: [email protected]

Title: COMPUTER PROGRAMMING 1 – (LECTURE/LABORATORY)


Module No. One (1)

I. Introduction
The module presents fundamental concepts of Computer Programming using the C language.
Lessons in this module includes a gentle introduction to computer programming basic concepts,
what a computer programming language is, what a program does, and what steps all programs
ultimately take to achieve a correct output.

II. Learning Objectives


After studying this module, you should be able to:
1. Define a formal language, the differences between high and low level computer languages, and
give examples of each.
2. Demonstrate an algorithm using a real world paradigm.
3. Describe the components that make up the average structure of an imperative program and how
they might map to a real world paradigm.
4. Describe and give full examples of the different types of errors that can occur in a computer
program, and attempt to map them to the same real world paradigm.

MODULE 1
[COMPUTER PROGRAMMING 1 MODULE] 3

5. Learn how a program is broken down into execution code and binary nature of instruction
execution.
6. Successfully perform programming using C and write the correct and running source code for a
given problem.

III. Topics and Key Concepts


The topics in this module includes ;
1.Lecture on the brief history of computer programming and the development of formal languages
while comparing and contrasting them to natural languages. And explain why computer languages
are necessarily formal.
2.Lecture on the nature of an algorithm and why it is necessary from a computing perspective.
Mapping of algorithms and pseudocodes with flowcharting is also part of the module.
3. Discussion on the Number System and Conversion.
3.Introduction of a program building blocks;input,output,math,conditional execution,repetition.
Programming errors of either programmer or environmental origin.

IV. Teaching and Learning Materials and Resources


To help attain the module learning objectives the following materials will be of relevant
importance;
1. Desktop or Laptop
2. Installed C Compiler or Online C Compiler or C Compiler Mobile App
3. Internet connection
4. Paper and Pen
5. Any book in C programming / Online Tutorials for reference.
V. Learning Task
Activity sheets are part of the module and are expected to be answered and submitted/ passed prior
to the next lesson. Lesson Activities focus on the following Five (5) E’s of Inquiry Based Learning
Model ; ENGAGE, EXPLORE, EXPLAIN, ELABORATE and EVALUATE.
VI. Reference
1. C Programming Language, GeeksForGeeks Online website (https://www.geeksforgeeks.org/c-
programming-language/ ).
2. Learn C Programming, Tutorialspoint Online website
(https://www.tutorialspoint.com/cprogramming/index.htm ).
3. C Tutorial – Learn C Programming with examples, BeginnersBook Online website
(https://beginnersbook.com/2014/01/c-tutorial-for-beginners-with-examples/).
4. C Programming Language Tutorial, java T point Online website (https://www.javatpoint.com/c-
programming-language-tutorial ).
5. The C Programming Language, University of Utah School of Computing Online website
(https://www.cs.utah.edu/~germain/PPS/Topics/C_Language/the_C_language.html).

1st Semester, A.Y. 2020-2021



4 [COMPUTER PROGRAMMING 1 MODULE]

Introduction

A computer is a machine that performs a variety of tasks


according to specific instructions. It is a programmable electronic
device, which accepts data or information via an input device, and
its processor manipulates the information at high speed according
to a program.

The computer has two major components. Hardware, which is


the tangible part of the computer. It is composed of electronic and
mechanical parts.

Software, which is the intangible part of a computer. It consists of


data and the computer programs.

Basic Components of a Computer

1. Hardware

The Central Processing Unit


The processor is the “brain” of the computer. It contains millions of extremely tiny electrical parts. It
does the fundamental computing within the system. Examples of processors are Pentium, Athlon and
SPARC.

Memory
The memory is where data and instructions needed by the CPU to do its appointed tasks can be found.
It is divided into several storage locations that have corresponding addresses. The CPU accesses the
memory with the use of these addresses.

1. Main Memory

The main memory is very closely connected to the


processor. It is used to hold programs and data, that the
processor is actively working with. It is not used for long-
term storage. It is sometimes called the RAM (Random
Access Memory).

The computer's main memory is considered as volatile


storage. This means that once the computer is turned off,
all information residing in the main memory is erased.

MODULE 1
[COMPUTER PROGRAMMING 1 MODULE] 5

2. The Secondary Memory

The secondary memory is connected to main memory. It is used to hold programs and data for long
term use. Examples of secondary memory are hard disks and cd/dvd drives, USB flash drives

Secondary memory is considered as non-volatile storage. This means that information residing in
secondary memory is not erased after the computer is turned off.

Main Secondary
Property
Memory Memory
Fast Slow Speed

Expensive Cheap Price

Low High Capacity

Yes No Volatile

Table 1: Comparison between main memory and secondary memory

Input and Output Devices


Input and output devices allow a computer system to interact
with the outside world by moving data into and out of the
system.

Examples of input devices are keyboard, mouse, microphone


Examples of output devices are monitor, printer and speaker

Software
Software is the program that a
computer uses in order to function. It is kept on some hardware device like a
hard disk, but it itself is intangible. The data that the computer uses can be
anything that a program needs. A Program acts like instructions for the
processor.

Some Types of Computer Programs:

1. Systems Programs

• Programs that are needed to keep all the hardware and software systems
running together smoothly

Examples:
• Operating Systems like Linux, Windows, Unix, Solaris, MacOSx

2. Application Programs

1st Semester, A.Y. 2020-2021



6 [COMPUTER PROGRAMMING 1 MODULE]

• Programs that people use to get their work done

• Examples:
• Word Processor
• Game Apps
• Compilers / IDEs

3. Utility Programs

• These are used to enhance the performance of the Computer System.


• Examples:
• Disk Defragmenter
• Disk Repair
• Network Managers

Overview of Computer Programming Languages

What is a Programming Language?

A programming language is a standardized


communication technique for expressing instructions to a
computer. Like human languages, each language has its
own syntax and grammar.

Programming languages enable a programmer to


precisely specify what data a computer will act upon,
how these data will be stored/transmitted, and precisely
what actions to take under various circumstances.

There are different types of programming languages that


can be used to create programs, but regardless of what
language you use, these instructions are translated into machine language that can be understood by
computers.

Kinds of Computer Programming Languages

1. Machine Language also called machine code, low-level language , in binary form which a
particular computer can execute directly.

2. Assembly Language is a low-level


programming language. Assembly language

MODULE 1
[COMPUTER PROGRAMMING 1 MODULE] 7

is converted into machine code executable with the help of an assembler program.

3. High Level Languages are machine independent. Design to be used by human or the programmer.
Programming style and context is easier to learn and implement. C/C++ and Java are examples.

4. System Language is used for system


programming, designed to write system
software and low level tasks, like memory
and process management. Nim, Rust, Go,
C/C++ are the best examples.

5. Scripting Language is an extremely high


level and powerful language. Used to write
scripts containing series of commands,
which are interpreted one at a time at
runtime. Scripting is generally used to make
dynamic web applications.

6. Visual Languages allow the user to create illustrations to describe various processes, manipulating
graphical elements rather than typing textual commands. Alice, Lego Mindstorms, Scratch are few
examples.

Programming Paradigms

A programming paradigm is the style or way of programming. A program can feature multiple
paradigms. These are the known programming paradigms;

Imperative: Approach
with an explicit sequence
of commands that update
state.
Declarative: Done with
specifying the result you
want, not how to get it.
Structured:
Programming with clean,
goto-free, nested control
structures.
Procedural: Is an
Imperative programming
with procedure calls.
Functional (Applicative): Using function calls that avoid any global state.
Function-Level (Combinator): Uses no variables at all.
Object-Oriented: Defines objects that send messages to each other. Objects have their own internal
(encapsulated) state and public interfaces. Object orientation can be:
Class-based and Prototype-based.
Event-Driven: Programming with emitters and listeners of asynchronous actions.
Flow-Driven: Programming processes communicating with each other over predefined channels.
Logic (Rule-based): Specifies a set of facts and rules. An engine infers the answers to questions.
Constraint: Specifies a set of constraints. An engine finds the values that meet the constraints.
Aspect-Oriented: Programming cross-cutting concerns applied transparently.
Reflective: Programming by manipulating the program elements themselves.
Array: Programming with powerful array operators that usually make loops unnecessary.

1st Semester, A.Y. 2020-2021



8 [COMPUTER PROGRAMMING 1 MODULE]

The Program Development Life Cycle

Programmers do not sit down and start writing


code right away when trying to make a
computer program. Instead, they follow an
organized plan or methodology, that breaks the
process into a series of tasks.

Here are the basic steps in trying to solve a


problem on the computer:

1. Problem Definition
2. Problem Analysis
3. Algorithm design and representation
(Pseudocode or flowchart)
4. Coding and debugging

In order to understand the basic steps in solving a problem on a computer, let us define a single
problem that we will solve step-by-step as we discuss the problem solving methodologies in detail.
The problem we will solve will be defined in the next section.

Problem Definition
A programmer is usually given a task in the form of a problem. Before a program can be designed to
solve a particular problem, the problem must be well and clearly defined first in terms of its input and
output requirements.

A clearly defined problem is already half the solution. Computer programming requires us to define
the problem first before we even try to create a solution.

Let us now define our example problem:

“Create a program that will determine the number of times a


name occurs in a list.”

Problem Analysis
After the problem has been adequately defined, the simplest
and yet the most efficient and effective approach to solve the
problem must be formulated.

Usually, this step involves breaking up the problem into smaller


and simpler sub-problems.

Example Problem:
Determine the number of times a name occurs in a list

Input to the program:


list of names, name to look for

Output of the program:


the number of times the name occurs in a list

MODULE 1
[COMPUTER PROGRAMMING 1 MODULE] 9

Algorithm Design and Representation

Once the problem is clearly defined, set to finding a solution. In computer programming, it is
normally required to express a solution in a step-by-step manner.

An Algorithm is a clear and unambiguous specification of the steps needed to solve a problem. It may
be expressed in either Human language (English, Tagalog), through a graphical representation like a
flowchart or through a pseudocode, which is a cross between human language and a programming
language.

Now given the problem defined in the previous sections, how do we express our general solution in
such a way that it is simple yet understandable?

Expressing our solution through Human language:


1. Get the list of names
2. Get the name to look for, let's call this the keyname
3. Compare the keyname to each of the names in the list
4. If the keyname is the same with a name in the list, add 1 to the count
5. If all the names have been compared, output the result

Expressing our solution through a flowchart

Figure 2: Example of a Flowchart


Expressing our solution through pseudocode:

Let nameList = List of Names


Let keyName = the name to be sought
Let Count = 0
For each name in NameList do the following
if name == keyName
Count = Count + 1
Display Count
Figure 2: Example of a Pseudocode

Flowcharting Symbols and Description


A flowchart is a design tool used to graphically represent the logic in a solution. Flowcharts typically
do not display programming language commands. Rather, they state the concept in English or
mathematical notation.
Here are some the commonly used symbols in creating flowcharts.

1st Semester, A.Y. 2020-2021



10 [COMPUTER PROGRAMMING 1 MODULE]

Table 2: Flowchart Symbols

Coding and Debugging

Symbol Name Meaning


Represents the process of executing a
defined operation or groups of operations
that results in a change in value, form, or
Process Symbol
location of information. Also functions as
the default symbol when no other symbol is
available.

Represents an I/O function, which makes


data available for processing (input) or
Input/Output displaying (output)of processed information.
(I/O) Symbol

Represents the sequence of available


information and executable operations.The
lines connect other symbols, and the
Flowline Symbol arrowheads are mandatory only for right-to-
left and bottom-to-top flow.

Represents the addition of descriptive


information, comments, or explanatory
Annotation notes as clarification. The vertical line and
Symbol the broken line may be placed on the left,
as shown, or on the right.

Represents a decision that determines which


of a number of alternative paths is to be
Decision Symbol followed.

Represents the beginning, the end, or a


point of interruption or delay in a program.
Terminal Symbol

Represents any entry from, or exit to,


Connector another part of the flowchart. Also serves as
Symbol an off-page connector.

Represents a named process consisting of


one or more operations or program steps
Predefined
that are specified elsewhere.
Process Symbol

After constructing the algorithm, it is now possible to create the source code. Using the algorithm as
basis, the source code can now be written using the chosen programming language.

Most of the time, after the programmer has written the program, the program is not 100% working
right away. The programmer has to add some fixes to the program in case of errors (also called bugs)
that occurs in the program. This process of is called debugging.

MODULE 1
[COMPUTER PROGRAMMING 1 MODULE] 1
1

There are two types of errors that a programmer will


encounter along the way. The first one is compile-time
error, and the other is runtime error.

Compile-Time Errors occur if there is a syntax error in


the code. The compiler will detect the error and the
program won't even compile. At this point, the
programmer is unable to form an executable that a user
can run until the error is fixed.

Forgetting a semi-colon at the end of a statement or misspelling a certain command, for example, is a
compile-time error. It's something the compiler can detect as an error.

Compilers are not perfect and so cannot catch all errors at compile time. This is especially true for
logic errors such as infinite loops. This type of error is called runtime error.

For example, the actual syntax of the code looks okay. But when you follow the code's logic, the same
piece of code keeps executing over and over again infinitely so that it loops. In such a case, compilers
aren't really smart enough to catch all of these types of errors at compile-time, and therefore, the
program compiles fine into an executable file. However, and unfortunately, when the end-user runs
the program, the program (or even their whole computer) freezes up due to an infinite loop. Other
types of run-time errors are when an incorrect value is computed, the wrong thing happens, etc.

Number Systems and Conversion

Numbers can be represented in a variety of ways. The


representation depends on what is called the BASE. The
following are the four most common representations.

Decimal
We normally represent numbers in their decimal form. Numbers
in decimal form are in base 10. This means that the only digits
that appear are 0-9. Here are examples of numbers written in
decimal form:
12610 (normally written as just 126)
1110 (normally written as just 11)

Binary
Numbers in binary form are in base 2. This means that the only legal digits are 0 and 1. We need to
write the subscript 2 to indicate that the number is a binary number. Here are examples of numbers
written in binary form:
11111102
10112

Octal
Numbers in octal form are in base 8. This means that the only legal digits are 0-7. We need to write
the subscript 8 to indicate that the number is an octal number. Here are examples of numbers written
in octal form:
1768
138

1st Semester, A.Y. 2020-2021



12 [COMPUTER PROGRAMMING 1 MODULE]

Hexadecimal
Numbers in hexadecimal form are in base 16. This means that the only legal digits are 0-9 and the
letters A-F (or a-f, lowercase or uppercase does not matter). We need to write the subscript 16 to
indicate that the number is a hexadecimal number. Here are examples of numbers written in
hexadecimal form:
7E16
B16

Hexadecimal 0 1 2 3 4 5 6 7 8 9 A B C D E F
Decimal Equivalent 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Table 3: Hexadecimal Numbers and their Equivalence to decimal numbers

Decimal Binary Octal Hexadecimal


12610 11111102 1768 7E16
1110 10112 138 B16
Table 4: Summary of Examples

Conversion Process

Decimal to Binary / Binary to Decimal


To convert a decimal number to binary, continuously divide the number by 2 and get the remainder
(which is either 0 or 1), and get that number as a digit of the binary form of the number. Get the
quotient and divide that number again by 2 and repeat the whole process until the quotient reaches 0
or 1. We then get all the remainders starting from the last remainder, and the result is the binary form
of the number.
NOTE: The last digit is already less than the divisor (which is 2) just copy the value to the remainder
portion.

For Example:
12610 = ? 2

Quotient Remainder
126 / 2 = 63 0
63 / 2 = 31 1
Write
31 / 2 = 15 1
it this
15 / 2 = 7 1
way
7 / 2 = 3 1
3 / 2 = 1 1
1 / 2 = 1

So, writing the remainders from the bottom up, we get the binary number 11111102

To convert a binary number to decimal, we multiply the binary digit to "2 raised to the position of the
binary number". We then add all the products to get the resulting decimal number.

For Example:
11111102 = ? 10

Position 6 5 4 3 2 1 0
Binary
1 1 1 1 1 1 0
Digits
0 x 20 = 0

MODULE 1
[COMPUTER PROGRAMMING 1 MODULE] 1
3

Position 6 5 4 3 2 1 0
1 x 21 = 2
1 x 22 = 4
1 x 23= 8
1 x 24= 16
1 x 25 = 32
1 x 26 = 64
TOTAL: 126

Decimal to Octal (or Hexadecimal)/Octal (or Hexadecimal) to Decimal


Converting decimal numbers to Octal or hexadecimal is basically the same as converting decimal to
binary. However, instead of having 2 as the divisor, you replace it with 8(for octal) or 16 (for
hexadecimal).

For Example (Octal):


12610 = ? 8

Quotient Remainder
Write
it
126 / 8 =
15 6 this
15 / 8 = 1 7 way
1/8= 1

So, writing the remainders from the bottom up, we get the octal number 1768

For Example (Hexadecimal):


12610 = ? 16

Writing the remainders from the bottom up, we get the hexadecimal number 7E16

Converting octal or hexadecimal numbers is also the same as converting binary numbers to decimal.
To do that, we will just replace the base number 2 with 8 for Octal and 16 for hexadecimal.

For Example (Octal):

Quotient Remainder
Write
14 (equal to hex digit E)
it
126 / 16 = 7 this
7 / 16 = 7 way

1768 = ? 10

Position 2 1 0
Octal Digits 1 7 6
6 x 80 = 6
7 x 81 = 56

1st Semester, A.Y. 2020-2021



14 [COMPUTER PROGRAMMING 1 MODULE]

Position 2 1 0
1 x 82 = 64
TOTAL: 126

For Example (Hexadecimal):


7E16 = ? 10

Position 1 0
Hex Digits 7 E
14 x 160 = 14
7 x 161 = 112
TOTAL: 126

Binary to Octal / Octal to Binary


To convert from binary numbers to octal, we partition the binary number into groups of 3 digits (from
right to left), and pad it with zeros if the number of digits is not divisible by 3. We then convert each
partition into its corresponding octal digit. The following is a table showing the binary representation
of each octal digit.

Octal Digit Binary


Representation
0 000
1 001
2 010
3 011
4 100
5 101
6 110
7 111

Table 5: Octal Digits and their corresponding binary represenation

For Example:
11111102 = ? 8

0 1 1 1 1 1 1 0

1 7 6
Equivalent octal number

Converting octal numbers to binary is just the opposite of what is given above. Simply convert each
octal digit into its binary representation (given the table) and concatenate them. The result is the
binary representation.

MODULE 1
[COMPUTER PROGRAMMING 1 MODULE] 1
5

Binary to Hexadecimal / Hexadecimal to Binary


To convert from binary numbers to hexadecimal, we partition the binary number into groups of 4
digits (from right to left), and pad it with zeros if the number of digits is not divisible by 4. We then
convert each partition into its corresponding hexadecimal digit. The following is a table showing the
binary representation of each hexadecimal digit.

Hexadecimal Binary
Digit Representation
0 0000
1 0001
2 0010
3 0011
4 0100
5 0101
6 0110
7 0111
8 1000
9 1001
A 1010
B 1011
C 1100
D 1101
E 1110
F 1111

Table 6: Hexadecimal Digits and their corresponding Binary Representation

For Example:
11111102 = ? 16

0 1 1 1 1 1 1 0

E
7
Equivalent Hexadecimal Number

1st Semester, A.Y. 2020-2021



16 [COMPUTER PROGRAMMING 1 MODULE]

Converting hexadecimal numbers to binary is just the opposite of what is given above. Simply convert
each hexadecimal digit into its binary representation (given the table) and concatenate them. The
result is the binary representation.

FLOWCHART EXAMPLES:

Example 1 Create a flowchart that will count from 1 to 10.

Start

Ctr = 0

B
Ctr=Ctr+1

No
Is Ctr =
B
10

Yes

End

Example 2 Draw a simple flowchart to show the


counting process of an integer 1 - 10 and add the
numbers.

Example 3. Create a
Flowchart that will print the sum and average of the given grade
Q1:35, Q2:50, Q3:60, Q4:35.

MODULE 1
[COMPUTER PROGRAMMING 1 MODULE] 1
7

Example 4: Given three numbers A, B and C. Draw a flowchart to compute and print out the sum,
the average, and the product of these values. A:5 ; B:8 ; C:10.

1st Semester, A.Y. 2020-2021



18 [COMPUTER PROGRAMMING 1 MODULE]

ACTIVITY 1

Name:_________________ Score/Rating:______________
Course:_______________ Date: ____________________

I. ENGAGE: Word Search Puzzle. Find and circle all of the words on the list hidden in the grid.
The words may be hidden in any direction.

ALGORITHM
API
BINARY
BUG
CODE
COMPILER
CPU
DATA
DEBUG
DECISION
ERROR
FLOWCHART
HARDWARE
INFORMATION
LOGIC
LOOP
MEMORY
PROCESSOR
PROGRAMMING
PSEUDOCODE
SEMANTIC
SOFTWARE
SYNTAX

II. EXPLORE: Writing Algorithms. Choose a partner (classmate), talk about the process and steps
in each of the tasks below and be able to write the algorithm, pseudo-code and draw the flowchart of
each.
1. Bake a Bread
2. Borrow a book in the library
3. Compute the average of three numbers.
4. Calculate and output the volume of a box with a length of 73 cm, width is 47 cm, and height is 29
cm.
5. Write an algorithm to print the tree below:

*
***
*****
*******

MODULE 1
[COMPUTER PROGRAMMING 1 MODULE] 1
9

6. Write an algorithm to read two numbers that represent the length of two sides of a right triangle;
compute and print the length of its hypotenuse.

7. Write an algorithm (and draw a flowchart) that reads three numbers, calculate and print the sum
and average.

8. Write an algorithm (and draw a flowchart) of the enrollment process in Gordon College.

9. Write an algorithm for taking a bath.

10. Write an algorithm for cooking your favorite dish.

III. ELABORATE: Number System Conversion. Convert the following and show complete
solution/process:
1. 198010 to binary, hexadecimal and octal
2. 10010011012 to decimal, hexadecimal and octal
3. 768 to binary, hexadecimal and decimal
4. 43F16 to binary, decimal and octal
5. BABE to binary, decimal and octal

IV. EVALUATE. Prepare for an Online Quiz.

1st Semester, A.Y. 2020-2021



20 [COMPUTER PROGRAMMING 1 MODULE]

BRIEF HISTORY OF C LANGUAGE

The C programming language was developed at Bell Labs during the early 1970's. Derived from a
computer language named B and from an earlier language BCPL. Initially designed as a system
programming language under UNIX it expanded to have wide usage on many different systems. The
earlier versions of C became know as K&R C after the authors of an earlier book, "The C
Programming Language" by Kernighan and Ritchie. As the language further developed and
standardized, a version known as ANSI (American National Standards Institute) C became dominant.
As you study this language expect to see references to both K&R and ANSI C. Although it is no
longer the language of choice for most new development, it still is used for some system and network
programming as well as for embedded systems. More importantly, there is still a tremendous amount
of legacy software still coded in this language and this software is still actively maintained.

WHY C?

• C is a small language. It does not have many


keywords and its standard libraries are not too big, yet
it is very powerful.

• C is the native language of the UNIX operating


system - a major operating system on large machines.

• It is usually the first high-level language available


on any new computer, including microcomputers,
minicomputers, and mainframes. It allows the
programmer a wide range of operations from high level
down to a very low level, approaching the level of
assembly language.

• C is the standard development language for personal computers. Many PC packages such as
database programs, graphics libraries etc. are written in C.

• C language supports structured and modular programming.

• C programs are generally quite portable.

The C syntax is a base for many other programming


languages, such as C++, Java, PERL and PHP. The last
two are the languages used to write programs on Web
servers.

MODULE 1
[COMPUTER PROGRAMMING 1 MODULE] 2
1

Structure of C Language Program

1. Comment Line - It indicates the purpose of the program. It is represented as


/*...................................*/. Comment line is used for increasing the readability of the program and is
use in explaining the program and generally used for documentation. Comment line can be single or
multiple-line but should not be nested. It can be anywhere in the program except inside string constant
and character constant.

2. Preprocessor Directive - #include<stdio.h> tells the compiler to include information about the
standard input/output library. It is also used in symbolic constant such as #define PI 3.14(value). The
stdio.h (standard input output header file) contains definition and declaration of system defined
function such as printf( ), scanf( ), pow( ) etc. Generally printf() function used to display and scanf()
function used to read value.

3. Global Variable Declaration -This is the section where variable are declared globally so that it can
be accessed by all the functions used in the program. And it is generally declared outside the function.

4. Main ( ) Function - Every function has one main() function from where actually program is started
and is enclosed within the pair of curly braces. The main( ) function can be anywhere in the program
but in general practice it is placed in the first position.
Syntax : The main function does not return any value
main() when void (means null/empty) as;
{................
........} void main(void ) or void main()
The main( ) function returns value when it {
declared by data type as; printf (“C language”);
int main( ) }
{
return 0 } Output: C language

The program execution starts with opening braces and end with closing brace. And in between the two
braces declaration part as well as executable part is mentioned. And at the end of each line, the semi-
colon is given which indicates statement termination.

{
Local variables;
Statements;
}
User defined function
}
}
/*First C program with return statement*/
#include <stdio.h>
int main (void)
{
printf ("Welcome to C Programming Language.\n");
return 0;
}

Output: Welcome to C Programming Language.


Steps for Compiling and Executing A Program

1st Semester, A.Y. 2020-2021



22 [COMPUTER PROGRAMMING 1 MODULE]

A compiler is a software program that analyzes a program developed in a particular computer


language and then translates it into a form that is suitable for execution on a particular computer
system. Figure 1. shows the steps that are involved in entering, compiling, and executing a computer
program developed in the C programming language.

Step 1: The program that is to be compiled is first typed into a file on the computer system using an
Editor or an IDE. There are various conventions that are used for naming files, typically be any name
provided the last two characters are “.c” or file with extension .c. So, the file name prog1.c is a valid
filename for a C program. An editor is usually used to enter the C program into a file. The program
that is entered into the file is known as the source program because it represents the original form of
the program expressed in the C language.

Step 2: After the source program has been entered into a file, then proceed to have it compiled. The
compilation process is initiated by typing a special command on the system. In the first step of the
compilation process, the compiler examines each program statement contained in the source program
and checks it to ensure that it conforms to the syntax and semantics of the language. If the compiler
discovers mistakes during this phase, they are reported to the user and the compilation process ends
right there. The errors then have to be corrected in the source program (with the use of an editor), and
the compilation process must be restarted. Typical errors reported during this phase of compilation
might be due to an expression that has unbalanced parentheses (syntactic error), or due to the use of
a variable that is not “defined” (semantic error).

Step 3: When all the syntactic and semantic errors have been removed from the program, the compiler
then proceeds to take each statement of the program and translate it into a “lower” form that is
equivalent to assembly language program needed to perform the identical task.

Step 4: After the program has been translated, the next step in the compilation process is to translate
the assembly language statements into actual machine instructions. The assembler takes each
assembly language statement and converts it into a binary format known as object code, which is then
written into another file on the system. This file has the same name as the source file, with the file
extension “o” (for object) instead of a “c”.

Step 5: After the program has been translated into object code, it is ready to be linked. This process is
once again performed automatically using the IDE. The purpose of the linking phase is to get the
program into a final form for execution on the computer. If the program uses other programs that
were previously processed by the compiler, then during this phase the programs are linked together.
Programs that are used from the system’s program library are also searched and linked together with
the object program during this phase. The process of compiling and linking a program is often called
building. The final linked file, which is in an executable object code format, is stored in another file
on the system, ready to be run or executed. Under Windows, the executable file usually has the same
name as the source file, with the c extension replaced by an .exe extension.

Step 6: When the program is executed, each of the statements of the program is sequentially executed
in turn. If the program requests any data from the user, known as input, the program temporarily
suspends its execution so that the input can be entered. Or, the program might simply wait for an
event, such as a mouse being clicked, to occur. Results that are displayed by the program, known as
output, appear in a window, sometimes called the console. If the program does not produce the
desired results, it is necessary to go back and reanalyze the program’s logic. This is known as the
debugging phase, during which an attempt is made to remove all the known problems or bugs from
the program. To do this, it will most likely be necessary to make changes to original source program.

MODULE 1

[COMPUTER PROGRAMMING 1 MODULE] 2
3

Figure 1. The Process of Writing a C Program


Source: https://www3.ntu.edu.sg/home/ehchua/programming/cpp/images/C_DevelopmentProcesses.png

Figure 2. Program Compilation and Execution

Why Learn C Programming?

C is everywhere. Almost every computer operating system is written in C, including smartphones and
other handheld devices. Most microcontrollers is programmed in C. C++, Objective C, and C# all are
built directly on top of C, and Python was written in it. A good knowledge of C will add points on
programmer’s resume.
Programming Tips for First Time C Programmers

1. Learn the Basic Variable Types

1st Semester, A.Y. 2020-2021



24 [COMPUTER PROGRAMMING 1 MODULE]

2. Learn the Operators


3. Learn and Use the C Standard Libraries
4. Know that C is unforgiving.
5. Debugging is your bestfriend.

It is essential to know what type of data you are


working with. It is a must to know that the
number 5 may be used as an integer or a
character type in a program. Data types and how
they are assigned to variables is an essential part
of every programming course. C uses many
operators for arithmetic, assignment, relational and logic among others. Using libraries in your C
source code is an essential programming practice. Just like in any other programming language,
Garbage In Garbage Out, C will do what you tell it, and instead of complaining when something does
not make sense even when the program executes, you might end up with some weird bugs. C will not
help you find what is wrong. To stop yourself from losing your mind, get comfortable with debugging
your codes.
Integrated Development Environment (IDE) and Compiler for C Programmers

Integrated Development Environment or IDE is an application or software which programmers use for
programming. It helps a programmer to program easily by providing all comprehensive facilities
required for the development of software. It can improve the productivity of a programmer or
developer because of its fast setup and various tools. An IDE includes three (3) parts, source code
editor; build automation tool (compiler) and a debugger. The source code editor is where
programmers write the codes, build automation tool is used by the programmers for compiling the
codes and the debugger is used to test or debug the program in order to resolve any errors in the code.
IDEs also comes with features like object and data modeling, unit testing, source code library, and a
lot more. Here are some of the IDEs and Compilers for C .

1. Visual Studio Code - One of the most popular in according to a survey done by Stack Overflow. It is
an open-source code editor developed by Microsoft for Windows, Linux and Mac OS. Visual Studio
Code is based on an Electron framework.
2. Eclipse - Powerful and useful IDE used by developers for C/C++ programming. It is an open-source
software which is simple and easy to use. Originally, it was used for Java Programming but now it is
used for various languages. Eclipse can run Windows, Linux and Mac OS.
3. Code::Blocks – It is a free, open-source IDE developed in C++ . An extensible and highly
customizable IDE that performs on all platforms including Linux, Mac and Windows. Any function
can be added to this IDE by installing or coding a plugin.
4. Dev-C++ - It is a full-featured IDE for C or C++ languages. Uses MinGW port of GNU Compiler
Collection (GCC) or any other GCC compilers.
5. Borland Turbo C - Turbo C is an IDE and compiler for the C programming language from Borland.
First introduced in 1987, it was noted for its small size, fast compile speed, comprehensive manuals
and low price. ***NOTE: Discussion in this module and program codes are written/run using
this compiler.
6. CppDroid – Simple C/C++ IDE and compiler for android devices. It is focused on learning
programming languages and libraries. This app is freely available.
7. Mobile C – A mobile application that supports C programming. This does not require internet
connection to run your codes. ***NOTE: You may use this App on your mobile phone to
write/run source codes in this module. A good alternative for learners without PC/Laptop.
8. Online C compilers - There are various C Compilers that are available online. These are good
alternatives for devices with limited resources (device storage and processors) but requires internet
connection. Online Compilers are embedded on websites that provides online tutorials.

The Borland Turbo C Compiler Environment

MODULE 1

[COMPUTER PROGRAMMING 1 MODULE] 2
5

Basic Parts of the Turbo C IDE

Figure 2. Turbo C Basic Interface

The edit window is where you type your program. The cursor moves while you type your program
statements and its positions in line and column are shown at the bottom of the edit window.

The close box of a window is the box in the upper left corner. Click this box to quickly close the
window. (Or choose Window | Close.)

The title bar, the topmost horizontal bar of a window, contains the name of the window and the
window number. Double-clicking the title bar zooms the window. You can also drag the title bar to
move the window around.

The zoom box appears in the upper right corner of the window. In the above screen, the window is in
regular size. Click it to zoom the window to the maximum size. Click it again to return the window
back to the normal size.

The Sub Menu

1st Semester, A.Y. 2020-2021



26 [COMPUTER PROGRAMMING 1 MODULE]

How to Compile and Run a C Program

Locate the TC.exe file and open it. Click File>New and then write your C Program as shown
below.
#include<stdio.h>
int main()
{
printf("hello World!");
return 0;
}

SOURCES:

https://cs.lmu.edu/~ray/notes/pltypes/

Save the program by pressing F2 on your keyboard or File Menu > Save, remember the file extension
must be “.C”. The screenshot below shows a filename as helloworld.C.

MODULE 1

[COMPUTER PROGRAMMING 1 MODULE] 2
7

Compile the program using ALT+F9 or Compile>Compile as shown below.

Press Ctrl+F9 using your keyboard to RUN or Select Run>Run using the menu bar. To view the
output of the program at the output screen, press ALT+F5.

Dissecting the C Program

The C program starts with #include <stdio.h>. This line includes the "standard I/O library"
into the program. The standard I/O library lets you read input from the keyboard (called "standard
in"), write output to the screen (called "standard out"), process text files stored on the disk, and so on.
It is an extremely useful library. C has a large number of standard libraries like stdio, including string,
time and math libraries. A library is simply a package of code that someone else has written to make
your life easier (will be discussed bit later).
The line int main() declares the main function. Every C program must have a function named
main somewhere in the code. You will learn more about functions shortly. At run time, program
execution starts at the first line of the main function.
In C, the { and } symbols mark the beginning and end of a block of code. In this case, the
block of code making up the main function contains two lines.
The printf statement in C allows you to send output to standard out (in this example, the
screen). The portion in quotes is called the format string and describes how the data is to be
formatted when printed. The format string can contain string literals such as "hello World! \n "
symbols for carriage returns (\n), and operators as placeholders for variables.
The return 0; line causes the function to return an error code of 0 (no error) to the shell that
started execution.

The Character Set, Identifiers

1st Semester, A.Y. 2020-2021



28 [COMPUTER PROGRAMMING 1 MODULE]

A character denotes any alphabet, digit or special symbol used to represent information. The
alphabets, numbers and special symbols when properly combined form constants, variables and
keywords. The figure below shows alphabets, numbers and special symbols which are characters
allowed in C.

Figure 3. C Valid Character Set

C Identifiers
Identifiers are user-defined words used to name entities like variables, arrays, functions,
structures and the like. These are the rules for naming identifiers;
1. Names should only consist of alphabets (can be upper and lower case), digits and underscore (_)
symbol.
2. The first character should be an alphabet or an underscore.
3. Names should not be a keyword in C.
4. C is case sensitive, the upper case and lower case are considered differently. HELLO, hello, Hello
are different identifiers.
5. Identifiers must be used in meaningful, descriptive manner. Use names to denote meaning and
description of entities such as value, net_salary, age, data etc. ANSI standard compiler can recognize
identifiers with 31 characters. Here are some invalid identifiers; 5cb, int, res#, avg no

Keyword
C Language has certain words reserved for
doing specific tasks, these words are known as
reserved word or keywords. These are predefined
which are written in lower case. Keywords cannot be
used as variable names, since they represent special
meaning in the C Language. Some examples are int,
short, signed, unsigned, default, volatile, float, long,
double, break, continue, typedef, static, do, for, union,
return, while, do, extern, register, enum, case, goto,
struct, char, auto, const etc.

Figure 4. C Keywords and Reserved Words

Data Types
Data type is a classification that specifies the type of value a variable can hold. Used for
declaring variables or functions of different types before its use. The type of a variable determines
how much space it occupies in storage and how the bit pattern stored is interpreted. There are four (4)
classifications of data types in C; Basic Built-In (int, float, double, char) Derived (pointer, array,
structure, union), Void(void), Enumeration(enum).

C Basic Data Types

MODULE 1

[COMPUTER PROGRAMMING 1 MODULE] 2
9

The C primary or fundamental types are the Integer, Floating Point and the Char Types.
The Integer types are further classified as the table shows.

Table 7. Classification of the Integer Data Type

When a variable declared is of type int, this can contain integral values only, values that do not
contain decimal places. A variable declared to be of type float can be used for storing floating- point
numbers (values containing decimal places). The double type is the same as type float, with twice the
precision. The char data type can be used to store a single character, such as the letter a, the digit
character 6, or a symbol. A variable declared as char can only store character type value.

A type qualifier ( size – short/long or sign – signed/unsigned) can be used together with the
specified variable data type. The sign qualifier unsigned is used when the number is always positive,
and when signed is used, number may be positive or negative. If not mentioned, then by default signed
qualifier is assumed. The range of values for signed data types is less than that of unsigned data type.
Because in signed type, the left most bit is used to represent sign, while in unsigned type this bit is
also used to represent the value. The table below shows the size and range of the different data types
on a 16-bit machine.

Table 8. Data Types Size and Range


Constants
A Constant is any value that cannot be changed during program execution. It is an entity that
does not change whereas a variable is an entity that may change. For example, a number 10 represents
a constant integer value. The character string "I love Programming in C.\n" is an example of a
constant character string. C constants can be divided into two major categories: Primary Constants and
Secondary Constants, and further categorized as the figure below shows.

1st Semester, A.Y. 2020-2021



30 [COMPUTER PROGRAMMING 1 MODULE]

Figure 5. Categories of Constants

Variables

Variable is a name used in a program to reference a location where a data or value is stored in
memory or storage. The value of the variable can be change during the execution. The rule for naming
variables is the same as naming identifiers. Before a variable is used in a program, it must be declared
first. Variable declaration specifies its name and data type. The range of the value that can be stored in
a variable depends on its data type.
Variable Declaration Example : int a; char c; float f;
Data Types Used : int, char, float Variable Names : a, c, f

When a variable is assigned an initial value during the declaration, it is called initialization of
variable. A variable is initialized with the assignment operator such as; Data type variable
name=constant; Example: int a=20; Or int a; a=20;

Expressions

An expression is a program statement that evaluates to a certain value. It is combination of


variables, constants, operators and function call. Expressions can be arithmetic, logical and relational.
Example:
int a= c+d is an arithmetic expression
c>b is a relational expression
d==b is a logical expression
func(x, z) is a function call

Operators

A symbol used to perform some operations on


variables, operands or with a constant. Operators may
require two (2) operands (binary) to perform an
operation or may require single operand (unary). Figure 6. Types of Operators

Operator Precedence, Associativity and Assignment

Operator Precedence dictates the order of evaluation of operators in an expression while


associativity defines the order in which operators of the same precedence are evaluated in an
expression. Associativity can be either from left to right or right to left.

MODULE 1

[COMPUTER PROGRAMMING 1 MODULE] 3
1

Table 8. Operator Precedence and Associativity


Source: overIQ.com
Examples:

ANS : -8

1st Semester, A.Y. 2020-2021



32 [COMPUTER PROGRAMMING 1 MODULE]

ACTIVITY 2

Name:_________________ Score/Rating:______________
Course:________________ Date: ____________________

I. EXPLORE: Choose a partner (classmate) to do this task. Using the C Compiler / IDE,
Compile, Debug and Run the program to get the Output as shown below. Note: Make sure to
identify and correct the errors in the program to get the expected program output.

Program:

#include <stdio.h>

int main()
{
int a, b, c;
a = 5;
b = 7;
c=a+b
printf("%d %d = %d\n, a, b, c);
return 0;
}

EXPECTED PROGRAM OUTPUT:

5 + 7 = 12

EXPLAIN: A. Answer the following questions.


1. List down the steps you made to create, through getting the output of the program above.
2. List down the steps to save a C source file.
3. How did you debug the program? List down the steps.
4. Why do you need to debug a program?
5. List down problems/challenges/issues you encountered during the process and write down the
solutions/process you performed to solve the issues/problems.

B. What are the Types of Operators? List down and discuss, include sample expressions in your
discussion.

ELABORATE: Compute for the final value of x. Show step by step solution.

x = (1+3-2)*3^2-1%1/(1-(1+2*1))

EVALUATE: Prepare for an Online Quiz.

MODULE 1

You might also like