Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Fundamentals of Programming

Download as pdf or txt
Download as pdf or txt
You are on page 1of 84

FUNDAMENTALS

of PROGRAMMING:
C / C++ LANGUAGE
Chapter 1

PROGRAMMING CONCEPTS
Program Planning and Development

Each program has to be well thought of. Instructions must be ordered in a logical
sequence that can easily be understood by the computer. The problem must be analyzed to
such a level of detail that all logical conditions that may be encountered during the process are
taken into consideration. Otherwise, wrong results will be obtained.

There are 5 stages in developing a program: (1) defining the problem; (2) designing a
solution; (3) writing the program; (4) compiling, debugging and testing the program; (5)
documenting the program.

Defining the Problem

The first step in defining a problem begins with recognizing the need for information.
This information may be a request for a solution to a particular problem. The problem is then
thoroughly analyzed in order to determine what is required of its solution.

To fully analyze the problem, there is a need to define what outputs are required of the
program. The programmer must determine what data are needed, what form they are to be in,
what information is to be outputted, and how the data are to be manipulated to produce this
output.

Defining a Solution

When the definition of the problem is finished, the design of the solution begins.
Designing the solution requires breaking the problem into discrete steps. This sequence of
steps, a strategy for solving the problem is called an algorithm.

Flowcharting

One way a programmer illustrates the sequence of steps in an algorithm is with a


flowchart. A flowchart is a graphical representation of the sequence of operations where a
computer is to perform. Flowcharting uses easily recognizable symbols to represent the type of
processing performed in a program.

Pseudocode

A pseudocode is a version of the instructions describing each step the computer must
follow. It is written in an abbreviated form of spoken language and there lies somewhere
commands written in ordinary English and those in a computer language.

Writing the Program


After the programmer has defined the problem and designed a solution, the next step is
to write the program in a specific programming language. Although the definition and solution of
the problem are independent of the programming language, the proposed solution to the
problem may limit the choices of languages that can be used.

Despite the fact that programming languages differ in the commands they use, most
high-level programming languages have certain types of programming statements in common.
These are comments, declarations, input/output statements, computations, transfer of control,
and comparison.

Comments are statements that have no effect on the program. They are simply used to
make the program easier to understand. They are inserted at key points in the program and
serve as an internal documentation of the program.

The programmer uses declarations to define items used in the program. Examples
include definitions of files, records, initial values, reusable functions and the like.

Input/output statement transfer data to and from the primary storage for use by the
program, as well as to and from other I/O devices like the monitor and the keyboard.
Commands such as READ and PRINT are examples of these types of statements.

Computational instructions perform arithmetic operations such as addition, subtraction,


multiplication, division and exponentiation. Different programming languages vary in the way
they invoke the computer’s arithmetic capabilities.

Another type of instruction allows the sequence of execution to be altered by transferring


control. A conditional transfer of control alters the sequence only when a certain condition is
met. An unconditional transfer of control always changes the sequence of execution.

Comparisons allow two items to be compared. Based on the result of the comparison,
input/output, computation, or transfer of control could occur.

As the program is being coded, the programmer should be aware that although
generating the correct output is the primary goal of the program, it is not the only requirement of
a good program. The programmer should try to incorporate the following qualities into any
program:
 Programs should be easy to read and understandable. Data names should be
descriptive. Statements should be placed in a format that is easy to read and follow.
Placing enough comments can help in making the program easier to understand.
 Programs should be efficient. Programs should execute as little time as possible.
 Programs should be reliable. Programs should consistently produce the correct
output. All formulas and computations, as well as all logic test and transfer control, must
be accurate.
 Programs must be robust. Programs should work under all conditions. Reliability alone
is no guarantee for a successful program. Internal logic maybe correct but an incorrect
data item could produce an incorrect output. For example, how a program would react if
a person’s age were 2, 45 or -54?
 Programs should be maintainable. They should be easy to update and modify.
Programs should be written in independent modules so that a change in one module
does not necessitate a change in others.
Compiling, Debugging and Testing the Program

Instructions must be translated into machine language before they can be executed. A
compiler is a special program for each programming language that is located into the computer
when that language is used. It translates each line of code into the machine instruction that can
be understood by the computer.

Documentation of the Program

Documentation consists of written descriptions and explanations of programs and other


materials associated with an organization’s data processing system. Documentation of a system
and program designs are one of the most important requirements for success in data
processing application. Proper program documentation serves as a guide for programmers and
analysts who must modify or update existing programs and system procedures.

The process of documentation is an ongoing one. It begins with the initial request for
information. The individual making the request should be identified. So should those responsible
for designing the system and required programs.

During the problem definition stage, the problem should be described clearly in a short
narrative statement. The objectives of the program should be included with the problem
statement. Several other descriptions are needed.

 A complete description of the contents and formats of all data inputs, outputs and files to
be used.
 A statement of the hardware requirements for running the program, as well as estimated
processing time and storage requirements.
 A statement of software requirements, such as utility programs and library programs.

In the planning phase, the most important documentation produced is the flowchart. Descriptive
comments may be included for each processing step. The test data used to test the program
should also be included.

Programming Language

A language is defined as a system for communication. Written language uses symbols


(that is, the characters) to build words. The entire set of words is the language vocabulary. The
language syntax and grammar define the way in which the words can be meaningfully
combined. The actual meaning of words is defined by the language semantics.
In computer science, human languages are known as natural languages. Unfortunately
computers are not sophisticated enough to understand natural languages. So in order for
humans to communicate with computers, we must communicate using special computer
language.

Types of Programming Languages

Machine Language
It is the only language that the computer understands. It consists only of numbers. Each
different type of CPU has its own unique machine language. A programming language, on the
other hand defines a vocabulary and a set of grammatical rules for instructing a computer to
perform specific tasks. Each language has a unique set of keywords and a special syntax for
organizing program instructions.

Programming Languages can be broadly classified as either high level programming


languages or low level programming languages. High level programming languages are more
complex than the language the computer actually understands. But they are simple compared to
human languages.

Machine Language is the lowest level programming language. It is the only language
understood by computers and consists of pure numbers. Machine language functions as the
target language of other language programs. The other language programs must be translated
into machine language before the computer can execute the instructions. Because the data in
digital computers is stored as either on or off electrical states, machine language takes the form
of either 1 or 0.

Low-Level Language

Low level languages are also called Assembly language and are similar to machine
language. But in contrast, assembly language is much easier to understand than a machine
language. Assembly languages were developed to overcome the disadvantage of machine
language. Instead of using 1’s and 0’s, to specify machine instructions, programmers use
mnemonics or machine op codes. The mnemonics are English-like abbreviations for the
machine language instructions.

Programmers who write low-level language programs must be highly skilled in two
areas. First, they must know a great deal about the internal workings of the microprocessor, and
a broad technical knowledge of the computer is needed. Secondly, the programmer must be
detailed oriented, every step of the computer must be coded and the actual numerical address
of the instructions and data must be specified.

High-Level Programming Language

High-level programming languages enable the programmer to write programs that are
more or less independent of a particular type of computer. Such languages are considered high-
level because they are closer to human language than the machine language the computer truly
understands. The main advantage of a high level language over low level language is that they
are easier to understand. They allow the programmers to focus on solving the problem rather
than knowing how to program the computer.

Ultimately, programs written in a high level language must be translated into machine
language. Examples of High Level Languages are C, FORTRAN and Pascal. Since their
development in the 1950’s, many other languages have been developed today. These include
Ada, Algol, BASIC, COBOL, C++, LISP and Prolog. Most programming languages were created
to serve specific purposes, such as teaching programming concepts, aiding in scientific
research, creating graphics or controlling input and output devices. However, programmers
found that languages could develop for one purpose, with few modifications serve equally well
in writing other programs.
The question of what programming language to use depends on the type of problem you
want to solve. Every language has its advantage and disadvantage. For example FORTRAN is
a good language for processing numerical data, but it is not good in organizing very large
programs. C language is a very good language for writing well-structured and readable
programs. C++ has a powerful object oriented capability but it is complex to learn.

Examples of High-Level Language

1. BASIC
BASIC is an acronym for Beginner’s All-Purpose Symbolic Instruction Code.
It was developed by John Kemeny and Thomase Kurtz in the early 1960’s. Their goal
was to create a language that could be easily learned and that would help students to
understand programming. BASIC is a simplified version of the first high-level language
that was FORTRAN.

Basic was generally implemented as an interpretive language, which is the


reason why it became the popular language for education. The student can learn in an
interactive way because of the immediate response for the correctness of the program
syntax.

An example of a BASIC program that will multiply two numbers, 243 and 87 and
printing the results is shown.

10 LET A = 87
20 LET B = 243
30 LET C = A * B
40 PRINT A; “ TIMES ” ;
50 PRINT B; “ = “; C
60 END

2. FORTRAN

FORTRAN is short for Formula Translator, and it is the oldest high-level


Programming language. It was developed in the mid-1960’s by John Backus when most
programs were written in either machine language or assembly language. At that time,
IBM supported the idea that programming language be developed that resembles the
English language and could be translated into machine language.

FORTRAN was primarily intended as high-level language used for programming


scientific, mathematical and engineering applications. The two most common versions of
FORTRAN are FORTRAN IV and FORTRAN 77. FORTRAN 77 was approved by ANSI
in 1978 and it contains features that are not available in the older version. Developed in
the early 1990’s FORTRAN-90 (to be followed by FORTRAN-95) is the latest version of
the FORTRAN language.

An example of a FORTRAN program that will multiply two numbers, 243 and 87
and printing the result is shown.

INTEGER A, B, C
A = 87
B = 243
C = A * B
WRITE (6,50) A, B, C
FORMAT (1X, I3M ‘ TIMES ‘, * I3, ‘=’ , I6)
STOP

3. COBOL
COBOL is short for Common Business-Oriented Language and it is the most
frequently used business programming language. It is used extensively in business,
education and government. COBOL was stated in the early 1960’s when a committee
led by the U.S. Department of Defense and other computer users and manufacturers,
known as CODASYL ( Conference of Data Systems Language ) wanted to develop a
common business programming language. They were the ones who established the
specifications for the COBOL language. Dr. Grace Murray Hopper was a major
contributor to the structure and development of the COBOL language. By mid 1960’s the
first commercial version of the COBOL language was offered. In 1968 ANSI published
guidelines for standardized COBOL that became known as ANSI COBOL.

An example of a COBOL program that will multiply two numbers 243 and 87
and printing the result is shown.

IDENTIFICATION DIVISION
PROGRAM-ID. SAMPLE.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE COMPUTER. IDIAC-747.
OBJECT COMPUTER. IDIAC-747.
DATA DIVISION.
WORKING–STORAGE SECTION .
01 A; PICTURE IS S9 (3) .
01 B; PICTURE IS S9 (3) .
01 C; PICTURE IS S9 (3) .
PROCEDURE DIVISION.
000–MAIN–LINE.
MOVE 87 TO A.
MULTIPLY B GIVING C.

4. PASCAL
PASCAL was the language named after the seventeenth century French
mathematician Blaise Pascal who constructed one of the first adding machines. It is a
high-level language developed by Nicklaus Wirth of Zurich Switzerland in the late
1960’s. Pascal is one of the first languages developed using a structured programming
approach. Pascal reflects a top-down modular programming design. It forces the
programmers to design programs methodically and carefully. It is for this reason that
Pascal became a popular teaching language. Pascal language is a balance between a
wordy language like COBOL and terse language like FORTRAN. Originally intended for
teaching purposes, Pascal rapidly expanded and was used in business and scientific
applications.
An example of a PASCAL program that will multiply two numbers, 243 and 87
and printing the result is shown.

PROGRAM SAMPLE;
VAR
A, B, C : INTEGER;
BEGIN
A := 87;
B := 243;
C := A * B;
WRITELN(OUTPUT, ‘ ‘, A, ‘TIMES’ , B, ‘ = ‘, C) ;
END.

5. C LANGUAGE
C is a high-level programming language developed by Dennies Ritchie at the
Bell Laboratories in 1972. The language was named C, because it was influenced by
another language called B developed by Ken Thompson. It was originally designed as a
systems programming language, which means that it was used to write operating system
programs. The UNIX operating system and its utilities were written in over 300,000 lines
of C code.

C is a popular language for writing system programs and applications software


for several reasons. C produces codes that run very fast compared to the other
languages, almost at the same speed as assembly language. This is also the reason
why the C language is referred to as a middle-level language. It provides the speed of
assembly language with high-level programming capabilities. C programs are also highly
portable; they are independent of the machine, so C codes can run on many different
computers. It can be implemented on small 9-bit computers. The language is also
compact, which requires only a small memory to run.

An example of a C program that will multiply two numbers, 243 and 87 and
printing the results is shown.

#include <stdio.h>
void main()
{
int a, b, c;
a = 87;
b = 243;
c = a * b;
printf(“\n%d times %d equals %d\n”, a,b,c);
}

6. C++ LANGUAGE
During the late 1980’s until the early 1990’s object-oriented programming
started to become popular. This led to the development of object-oriented languages:
Object-Pascal, Modula-2, Mesa, Cedar, Neon, Objective-C, LISP and C++. C++ was
developed by Bjarned Stroustrup while working at the Bell Laboratories. C++ is actually
an extension of C, and while it is not entirely a new language, significant extensions to
the C language have been adopted. C++ is considered a superset of C, and it has the
same capabilities as C with added object-oriented features. C++ is a powerful language,
but the languages still has the flexibility and efficiency of C with added support for
creating object classes. Although C++, was originally designed to aid in the management
of very large programs, its applications are not limited to this. The object-oriented
capabilities of C++ can be applied to virtually any programming task. C++ is one of the
most powerful and efficient programming languages today.

An example of C++ program that will multiply two numbers, 243 and 87 and
printing the result is shown.

#include <iostream.h>
void main()
{
int a = 243, b = 87, c;
c = a * b;
cout<< a<<” times “<<b <<” equals “ << c;
}

7. JAVA
The JAVA programming language is the popular programming for creating
applications on the Web. These applications are called “applets” because they are small
application program. Before the development of Java web pages were viewed as static
documents on the Web browser. These “static” web pages were creating using HTML
(Hypertext Markup Language) and most companies organize web pages using CGI
(Common Gateway Interface).

Java, whose original name was Oak, was developed in December 1990 by Un
Microsystems. Java was created as a programming tool, part of the Green project of Sun
whose task was to create something new and exciting. The original team members of
the Green project (also known as the secret “Green Team”) were Patrick Naughton, Bill
Joyo and James Gosling and were later joined by Chris Warth, Ed Frank and Craig
Forrest.

Interpreters and Compilers

Regardless of what type of language you use, eventually you will convert your programs
into a machine language so that the computer can understand it. When we write our programs
in a high-level language the computer cannot understand the language because it only operates
in bit. There is a need for translation process that will convert the programs written in high-level
language into machine language. There are two ways of doing this either compile the program
or interpret the program. Compiling and interpreting a program can be accomplished by using
other programs called compilers and interpreters, these programs translate the program written
into a machine language.

Compiler

A compiler is a program that translates a program written in a high-level language


(source code) and translates it into machine language (object code). The compiler derives its
name from the way it works. It analyzes the entire piece of source code and then re-organizes
the instructions and then translates it into machine code.
Every high-level programming language (except strictly interpretive languages) comes
with a compiler. In effect, the compiler is the language, because it defines which instructions are
acceptable and which are not.

Interpreter

The most common way to translate a high-level language to machine language is to


compile the program; other method is to pass the program through an interpreter. The
interpreter translates and executes the program line by line. An interpreter translates into an
intermediate form, which it then executes. In contrast, a compiler translates high-level
instructions directly into machine language.

The advantage of an interpreter, however, is that it does not need to go through the
compilation stage during which machine instructions are generated. This compilation process
can be time-consuming if the program is long. The interpreter, on the other hand, can
immediately execute high-level programs.

Student’s Name: Year/Section:


Instructor’s Name: Date:

____Chapter 1_____
EXERCISE 1

Answer the following questions on the space provided.

1. Enumerate the 5 stages in developing a program and briefly explain what is done in
each stage.
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________________________________________________
2. Define Algorithm.
____________________________________________________________________________
_________________________________________________________________________________________
_________________________________________________________________________________________________
_________________________________________________________________________________________________
_________________________________________________________________________________________________
_________________________________________________________________________________________________
_____

3. Define and explain a Pseudocode.


____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________________________

4. Differentiate the different types of programming language. What are the advantages of
high-level compare with low level languages.
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________________________________________
Student’s Name: Year/Section:
Instructor’s Name: Date:

____Chapter 1____
EXERCISE 2

Answer the following questions on the space provided.

1. What are the things that a programmer must know in order to solve a problem?
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________________________________________
2. What is a programming language?
_________________________________________________________________________________________________________
_________________________________________________________________________________________________
_________________________________________________________________________________________________
_________________________________________________________________________________________________
_________________________________________________________________________________________________
_________________________________________________________________________________________
_________________________________________________________________________________________________

3. What is the lower level of language that the computer can understand?
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________________________________

4. What is the meaning of BASIC?


_________________________________________________________________________________________________________
_________________________________________________________________________________________________
_________________________________________________________________________________________________
_________________________________________________________________________________________________
_________________________________________________________________________________________________
_________________________________________________________________________________________________
_________________________________________________________________________________________________
_________________________________________________________________________________________

5. Why is C language called a middle-level language?


____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________________________________________

6. Give the two methods of program translation from high-level language to machine
language.
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________________________________________

7. What are the advantages of a compiler over an interpreter?


____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________________________________________________

Chapter 2

FLOWCHARTING

A flowchart is an organized combination of shapes, lines, and text that graphically


illustrates a process or structure.

A flow chart is a graphical or symbolic representation of a process. Each step in the


process is represented by a different symbol and contains a short description of the process
step. The flow chart symbols are linked together with arrows showing the process flow direction.

A flowchart is a diagrammatic representation that illustrates the sequence of operations


to be performed in order to get the solution of a problem. Flowcharts are generally drawn in the
early stages of formulating computer solutions. Flowcharts facilitate communication between
programmers and business people. These flowcharts play a vital role in the programming of a
problem and are quite helpful in understanding the logic of complicated and lengthy problems.
Once the flowchart is drawn, it becomes easy to write the program in any high level language.

COMMON FLOWCHARTING SYMBOLS

Symbol Symbol Name Symbol Description


(Alternate Shape Name)

Process Show a Process or action step. This is the


most common symbol in both process
flowcharts and business process maps.

Predefined Process A Predefined Process symbol is a marker


(Subroutine) for another process step or series of
process flow steps that are formally defined
elsewhere. This shape commonly depicts
sub-processes (or subroutines in
programming flowcharts). If the sub-process
is considered “known” but not actually
defined in a process procedure, work
instruction, or some other process flowchart
or documentation, then it is best not to use
this symbol since it implies a formally
defined process.

Preparation As the names states, any process step that


is a Preparation process flow step, such as
a set-up operation.
Flow Line Flow line connectors show the direction
(Arrow, Connector) that the process flows.

Terminator Terminators show the start and stop


(Terminal Point, Oval) points in a process. When used as a Start
symbol, terminators depict a trigger action
that sets the process flow into motion.

Decision Indicates a question or branch in the


process flow. Typically, a Decision flowchart
shape is used when there are 2 options
(Yes/No, No/No-Go, etc.)

Connector In flowcharts, this symbol is


typically small
(Inspection) and is used as a Connector to show
a jump
from one point in the process flow to
another. Connectors are usually labeled
with capital letters (A, B, AA) to show
matching jump points. They are handy for
avoiding flow lines that cross other shapes
and flow lines. They are also handy for
jumping to and from a sub-processes
defined in a separate area than the main
flowchart.

Off-Page Off-Page Connector shows continuation of


Connector a process flowchart to another page. When
using them in conjunction with Connectors,
it’s best to differentiate the labels, e.g. use
numbers for Off-Page Connectors and
capital letters for Connectors. In actual
practice, most flowcharts just use the
Connect shape for both on-page and off-
page references.

Data (I/O) The Data flowchart shape indicates


inputs to and outputs from a process. As
such, the shape is more often referred to as
an I/O shape than a Data shape.

The following are some guidelines in flowcharting:


a. In drawing a proper flowchart, all necessary requirements should be listed out in logical
order.
b. The flowchart should be clear, neat and easy to follow. There should not be any room for
ambiguity in understanding the flowchart.
c. The usual direction of the flow of a procedure or system is from left to right or top to
bottom.
d. Only one flow line should come out from a process symbol.

or

e. Only one flow line should enter a decision symbol, but two or three flow lines, one for
each possible answer, should leave the decision symbol.

<0 >0

=0

f. Only one flow line is used in conjunction with terminal symbol.


g. Write within standard symbols briefly. As necessary, you can use the annotation symbol
to describe data or computational steps more clearly.
-------- This is top secret data

h. If the flowchart becomes complex, it is better to use connector symbols to reduce the
number of flow lines. Avoid the intersection of flow lines if you want to make it more
effective and better way of communication.
i. Ensure that the flowchart has a logical start and finish.
j. It is useful to test the validity of the flowchart by passing through it with a simple test
data.

FLOWCHARTING EXAMPLES

start

1. Input two numbers


num1=0 and display the sum
num2=0

input num1

sum = num1 + num2

print sum

end
start

2. Create a flowchart that will


area = 0 compute and display the area and
perimeter = 0 perimeter of a square

Area = side2
input side Perimeter = 4 * side

area = side * side


perimeter = 4 * side

print area

end

SAMPLE FLOWCHARTING WITH DECISION

start Create a flowchart that will


input age and print the string
can vote if the age is >=
age = 0 (greater than or equal to) 18
otherwise print the string
cannot vote
input age

T
age >= 18 print “can vote”

print “cannot vote”

end
start
Create a flowchart that will
input two integer values and will
num1 = 0
print the higher number/value.
num2 = 0

input num1

T
num1 > num2 print num1

print num2 end

SAMPLE FLOWCHARTING WITH LOOP

start
Create a flowchart that will
print the numbers from 1 to
10.
ctr = 1

F
ctr < = 10 end

T T

print ctr

ctr = ctr + 1
start
Create a flowchart that will
print even numbers from 1 to
x=2 10.

x < = 10 end

T
print x

x=x+2

Student’s Name: Year/Section:


Instructor’s Name: Date:

____Chapter 2____
EXERCISE 1

1. Create a flowchart that will input two (2) numbers and display the sum, product,
difference and quotient.
2. Create a flowchart that will compute and display the area and circumference of a circle.
Note:
Area = pi * r * r
Circumference = 2 * pi * r

3. Create a flowchart that will compute and display the area and perimeter of a rectangle.
Note:
Area = length * width
Perimeter = 2 (length + width)

4. Create a flowchart that will input a number in feet, convert and display the number in
inches.
5. Create a flowchart that will ask the user to input a number in feet and display the number
in yards.

Student’s Name: Year/Section:


Instructor’s Name: Date:

____Chapter 2____
EXERCISE 2

1. Create a flowchart that will input three (3) numbers and display the highest number.
(assume no equal values.)
2. Create a flowchart that will input a number and display “even” if the number is an even
number and “odd” if the number is an odd number.

3. Create a flowchart that will input a number and will print “Divisible” if the number is
divisible by 5, otherwise print “Not Divisible”.

4. Create a flowchart that will ask the user to input a character “m” or “f” and will display
“Hello Sir” if the input is “m” otherwise “Hello Madam”.
5. Create a flowchart that will input grade and will display “Passed” if the grade is 75 or
higher, otherwise it will display “Failed”.

Student’s Name: Year/Section:


Instructor’s Name: Date:

____Chapter 2____
EXERCISE 3

1. Create a flowchart that will print all odd numbers from 15 to 48.

2. Create a flowchart that will input a starting number and an ending number and will print
all even numbers within the two numbers.
3. Create a flowchart that will print all numbers divisible by five (5) starting from 257 down
to 189.

4. Create a flowchart that will print the following numbers: 120, 100, 80, 60, 40, 20.

5. Create a flowchart that will print all even numbers from 10 to 26 and display how many
numbers were generated.
6. Create a flowchart that will display the sum of all numbers from 1 to 15.

Chapter 3
INTRODUCTION TO
C LANGUAGE

It is a general purpose and structured programming language that includes certain low level
features that are normally available only in assembly or machine language.

Historical Background of C

C was developed in the 1970’s to be originally used with the UNIX operating system by
Brian W. Kernighan and Dennis M. Ritchie. Kernighan and Ritchie gave the classic definition of
C in their book “THE C PROGRAMMING LANGUAGE”. Five years later ANSI (American
National Standards Institute) defined and developed a new standard for the C programming
language. Several Compilers were developed to implement the ANSI standard, among them
were:

Microsoft C Borland C
Turbo C AT & T C

The birth of a new paradigm in programming, Object Oriented Programs (OOP), paved
the way to new versions of the language with object oriented capabilities like:

 Borland C++
 Turbo C++
 Microsoft Visual C++
The milestones in C’s development as a language are listed below:

 UNIX was developed c. 1969 – DEC PDP-7 Assembly Language


 BCPL a user friendly OS providing powerful development tools developed from BCPL.
Assembler tedious long and error prone.
 A new language “B” a second attempt. c. 1971
 By 1973 UNIX OS almost totally written in “C”.

Characteristics of C

 Small in size
 Structured language
 Low level (BitWise) programming readily available
 Pointer implementation – extensive use of pointers for memory, array,
 Structures and Functions

C has now become a widely used professional language for various reasons.

 It has high-level constructs.


 It can handle low-level activities.
 It produces efficient programs.
 It can be compiled on a variety of computers.

C Program Structure

A C program basically contains the following:

1. Headers
The segment of a C program where libraries are included in the compilation
process and where macros to be defined are written and stated. It may contain the
following:
a. Preprocessor. A system program that modifies a C program prior to its
compilation.
b. Preprocessor directive. A C program line beginning with # that provides an
instruction to the preprocessor.

The two most commonly use directives are:

#include – for libraries used in the program.


#define – for constant macro definitions.

A constant macro is a name that is replaced by a particular constant value before the
program is sent to the compiler.

Example
#define pi_value 3.14159
#define k 2
Note: The contents of a named constant memory location cannot change during program execution.

2. Declaration
All functions, variables, units or objects that contain values or group of values
must be made known to the computers so that memory spaces will be allocated for each
of them.

3. Functions
These are parts of a C program that performs a specific task. The task assigned
to a function is performed whenever C encounters the function name. In C, there should
be at least one function and it is the function main.

The function main() in C language declares the main program and call other functions.

Note: C is case sensitive!

4. Comments
These are remarks and non executable phrases or sentences.

Importance of Comments on Programs

 Program documentation contains information that enhances the readability of the


program.
 Comments are part of program documentation because they help others read and
understand the program. The compiler, however, ignores comments and they are not
translated into machine language.

Types of Comments:

 Multiple line comments – are comments enclosed by /* and */.


 Single line comments – are comments placed after // symbols.

Identifiers

Identifiers are names given to various program elements, such as variables, functions
and arrays. The following are the guidelines in creating identifiers:

 It consists of letters and digits without space, in any order, except that the first character
must be a letter.
 Uppercase and lowercase are permitted but they are not interchangeable. As an
exception, an underscore may be used as the first character of the identifier.
 Reserved words and standard functions must not be redefined.

Example of Valid Identifiers


X num_1
y1 _area
NAME Sum

Example of Invalid Identifiers Reason for Invalidity

1st starts with a digit


tax rate contains space
$Area contains a special character
void main a reserved word
int must not be redefined

Reserved Words

Reserved words are keywords that have standard predefined meaning in C. These
reserved words can be used only for intended purpose and they cannot be used as programmer
defined identifiers.

printf scanf int struct


goto void main long switch
auto do register typedef
break else return union
case enum short unsigned
char extern signed void
const float sizeof volatile
continue for static while
default goto include struct
do if int double

Basic Data Types

There are four basic data types in C as shown in the table below:

Typical Memory
Data Type Description
Requirements
int positive and negative numbers without decimal 2 bytes or 1 word (varies from
point one computer to another)
char single character 1 byte
float number containing decimal point and or
4 bytes
exponent
double double precision floating point number (higher
8 bytes
precision)

Type Modifiers / Qualifiers

In order to give more flexibility and extend the range of the various data types there are
four type qualifiers:
 signed
 unsigned
 long
 short

The modifiers long and short have been covered for integers. Prior to the ANSI standard
there were similar modifiers for floats. However, the introduction of double removed the
requirement for a long float. This is why a double has the format command % If in the printf()
and scanf() functions.

It is, however, now possible to declare a long double which uses 16 bytes of storage and
has approximately 24 digits of precision.
The signed and unsigned qualifiers are used to remove the special meaning assigned to
the first bit of storage for char and int. By default these are signed. If the first (signed) bit is zero
the number is positive, if it is one the number is negative. The effect of making a variable
unsigned is that the first bit becomes part of the positive number, thus extending the possible
range above zero. The full list of ranges can be seen in the table given.

Type Format Length Range Precision


unsigned char %c 8 bits 0 to 255 -
char %c 8 bits -128 to 127 -
unsigned int %i or %d 16 bits 0 – 65535 -
short int %i or %d 16 bits -32,768 to 32,767 -
int %i or %d 16 bits -32,768 to 32,767 -
unsigned long %lu 32 bits 0 to 4,294,967,295 -
long %ld 32 bits -2,147,483,648
-
to 2,147,483,68
float %f 32 bits 3.4 X 10 –38 to 3.4 X 10 +38 6 digits
double % If 64 bits 1.7 X 10 –308 to 1.7 X 10 +308 12 digits
long double %If 80 bits 3.4 X 10 –4932 to
24 digits
3. X 10 +4932

sizeof Function

There is a C function called sizeof which returns the number of bytes allocated to the
variable or data type given in the operand. For example,

sizeof(char) would return the value 1;


sizeof(float) would return the value of 4
sizeof(double) would return the value 8

Variable

A variable is an identifier whose value is allowed to change during the execution of a


program.

Variable Declaration

Every variable must be individually declared (or defined) before it can appear in a
program.

The syntax is:


data type variable list;
Example:

int x, y, z; //x, y and z are variables that store integer values


char a, b, c //a, b and c are variables that store char values

Variable Initialization

A variable can be given a value at the time of declaration. This is known as initialization.

Example:

int sum = 0; //line 1


char mi = ‘S’; //line 2

The statement labeled line 1 initializes an integer variable sum with the value zero.
The statement labeled line 2 initializes a char variable mi with the value ‘S’.

Input and Output Statement in C

The standard C library contains two functions that perform formatted input and output.
These are:
 printf () which writes to the screen
 scanf () which reads data from the keyboard

The term formatted means that these functions can read and write data in various
formats that the programmer decides.

The header file associated with the standard input and output is stdio.h. Any program
using these functions must incorporate this header file in the preprocessor directives.

printf () function

printf () has the following forms:

printf (“Control String”, Argument List);

The Gotoxy() Function

It is a function or procedure that positions the cursor at (X,Y), X in horizontal, Y in


vertical direction relative to the origin of the current window. The origin is located at (1,1), the
upper-left corner of the window.

The sample code below shows how to use the gotoxy function in C to move the text
cursor to a different location on the screen Code.

#include<stdio.h>
#include<conio.h>
int main (void)
{
int i;
printf (“This is the first line. \n”);
gotoxy (10, 4);
printf(“This is the second line. \n”);
gotoxy (20, 8);
printf(“And this is line 3. \n”);
return 0;
}

The Control String

The control string in the printf() function can contain three types of characters:

 Literal text to be printed


 Format commands beginning with a % which indicates the data type to be printed
 Escape sequences beginning with a left switch (\) to help format the literal text
and data.
Any item in the control string which is not proceeded by a % or \ will be printed literally to
stdout (standard output, normally the screen).

Format Commands

The format commands can be used in any combination as long as the number of
arguments exactly matches the number of format commands. Commas separate successive
arguments from each other. For example:

printf(“Code %c%d : Price %f : Product %s \n”, ‘D’, 1416, 1.67, “Ink” );

This gives the output:


Code D1416: Price 1.670000: Product Ink

Scientific Notation

Floating point values may be displayed in scientific notation. In this case, %e or %E will
be used as the control string.

Example

float a = 0.000435;
printf(“0.000435 in scientific notation form is %e or %E”,a,a);

Output
0.000435 in scientific notation form is 4.350000e-4 or 4.350000E-4

Note: Single characters need to be marked with single quotes and strings in doubles.

%c Single Character
%s String of Characters
%d Decimal
%i Integer (same as %d)
%f Decimal Floating Point Number
%e Scientific Notation
%g Uses %e or %f, whichever is shorter
%o Octal
%u Unsigned Decimal
%x Hexadecimal
%% Percent Sign
%p Pointer

Format Commands for printf() and scanf().

The program format.c demonstrates the format commands in printf

#include<stdio.h>
void main ()
{
printf(“This is a single character : %c \n”, ‘A’);
printf(“This is a string : %s \n”, “Hello World”);
printf(“This is a decimal number : %d \n”, 24);
printf(“This is a floating point number : %f \n”, 37.51);
}

Output:
This is a single character : A
This is a string : Hello World
This is a decimal number : 24
This is a floating point number : 37.510000

There are two format command modifiers to printf() which allow it to display either short
or long integers.

A short integer has the format command %d and a long integer has the format command
%ld.

Field Width Specifier

It is possible to specify a minimum field width for a particular type of field. Placing a
number between the % sign and the format character (d, c, s, or f) does this. If the value of the
argument takes fewer characters than the width then the field will be right justified and padded
with spaces.

It is possible to pad the field with zeros by placing a decimal point and a number after
the number specifying the field width. Various examples can be seen in the program field.c in
the next page.

Truncated Fields (Strings and Integers only)


In strings or integers there is another formatting option which allows for a field to be a
maximum length. This means that any value which has more characters than the field width will
be truncated. This is achieved by using a decimal point before the field width specifier.

It is possible to combine minimum field widths. This has the effect of truncating field
values to the correct length while padding the field with requisite number of leading spaces.
These can also be seen in the program field.c.

Formatting Values of type int

Add a number between the % and the d of the %d placeholder for the integer in the printf
format string. This number specifies how many columns are to be used for the display of the
digits, the field width. Values are right justified.

Value Placeholder Printed Output


234 %4d #234
234 %5d ##234
234 %1d 234
234 %8.4d ####0234
234 %1.4d 0234
234 %.4d 0234
-234 %4d -234

- (minus sign is counted in the digits to be displayed)

Formatting Values of type double (n,mf) n = total field width, m = desired number of decimal
places
Value Placeholder Printed Output
3.14159 %5.2f #3.14
3.14159 %4.2f 3.14
3.14159 %5.1f ##3.1
3.14159 %5.3f 3.142
3.14159 %.4f 3.1416
0.1234 %4.2f 0.12
-0.006 %4.2f -0.01
-99.42 %6.2f -99.42
0.123 %6.2f ##0.12
-9.536 %6.2f #-9.54
-25.554 %6.2f -25.55
99.999 %6.2f 100.00
999.4 %6.2f 999.40

The program field.c demonstrates the use of field width specifiers and justification.

/* field.c a program that demonstrates the use of field width


specifiers and justification */
#include<stdio.h>

void main ()

printf(“This is a string in a 10 character space :%10s\n”, “Hello”);


printf(“This is a short integer in a 5 character space :%5d\n”, 21);
printf(“This is short integer padded with zeros :%05d\n”, 24);
printf(“This is a left justified string :%-10s\n”, “Hello”);
printf(“This is a string with truncated field :%.8s\n”, “Hello
World”);
printf(“This shows a truncated field with padding :%10.8s\n”, “Hello
World”);
printf(“This shows a floating point number to 2 places :%.2f\n” ,
37.1723);

}
Output:
This is a string in a 10 character space: Hello
This is a short integer in a 5 character space: 21
This is short integer padded with zeros: 00024
This is a left justified string: Hello
This is a string with a truncated field: Hello Wo
This shows a truncated field with padding: Hello Wo
This shows a floating point number to 2 places: 37.17

Decimal Places (Floating Point Numbers)

In floating point numbers the use of a decimal point before the field width specifier is
different from its use in strings and integers. It means that the field should be printed only to that
number of decimal places (the default is 6).

Escape Sequences

To provide even more formatting in printing, there are various escape sequences. The
most common is \n which is the escape sequence to print a newline character. This is taken
from UNIX. The full list of escape sequences can be seen in the table below.

\a Alert (bell)
\b Backspace
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
\’ Single quote
\” Double quote
\\ Left switch
\0 Null

Escape Sequences for printf().


scanf ()

As printf() writes to the screen (or stdout) scanf() reads input from the keyboard (or
stdin). It has the same general form and uses the same format commands. However, where
printf() writes the value directly to the screen, the scanf() function needs to know where to write
the input value from stdin to their memory address. This is achieved by using the operator &
meaning address of. For example, to read a value from stdin into a short integer called hicount
the scanf() function call would be:

scanf(“%d”, &hicount);

Another important part of the scanf() function is the use of white spaces.

White Space Characters

Any number of spaces, tabs, or newline characters is white spaces. This includes
combinations of the three. Therefore, if 3 integers are to be received, then scanf() will continue
to wait until a non-white space character is typed. For example,

scanf(“%d %d %d”, &hinum1, &hinum2, &hinum3);

, will wait until all three values have been entered separate by white space. The three
distinct values will be assigned to variables hinum1, hinum2, hinum3, respectively.

Non-White Space Characters

A non-white space character in the control string will be read and ignored if it is matched
exactly in the input string. If not, the function will be terminated. For example,

scanf(“%d , %d”, &hinum1, &hinum2);

,will require the two input numbers to be separated by a comma. The comma must be
typed during the input string. It is possible to say that there will be a character that separates the
two variables, but the exact character is unknown. This is usually done for dates which is
achieved by using the * to suppress the assignment of the value. For example,

scanf(“%d*c%d”, &hinum1, &hinum2);

,would allow input of 10:20, 10/20 or 10,20. The middle character must be present, but is
effectively ignored. This also applies if a white space character is entered, hence 10 20 would
also match this statement.

String Addresses

A string is, in fact, only an array of characters. The base name of an array is its address.
Therefore, when allocating values to string using scanf() there is no requirement to use the
address-of (&) operator. This is shown in the following example:

scanf(“%s”, cname);
It is important to note that the string is read only to the first white space character. Any
spaces would mean that a second part to the name would be ignored. It is possible to limit the
maximum number of characters read into a string by placing a specifier before the format
command for the string:

scanf(“%15s”, cname);

Other Input / Output Functions for Characters

getch()function

gets a character from console but does not echo to the screen

Example
ch = getch(); a character input is assigned to ch even without entering a white
space

getche()function

gets a character from console and echoes to the screen

Example
ch = getche(); a character input is assigned to ch even without entering a white
space and displays the character to the screen

putchar() and putch() function


prints a character to the screen.

putchar(ch); or putch (ch); is functionally equivalent to printf(“%c”, ch);

Assignment Operator

This operator is denoted by a single equals sign ( = ) and is used in assigning values to
variables.

Assignment Statement

The syntax is:

variable_name = value;

This statement assigns the value on the right to the variable named on the left. Consider
the given example.

int x, y, z;

z = 5; x = 6; y = 4; // line 1
x = x + y; // line 2 x gets the value of 10
y = y + 5; // line 3 y gets the value of 9
The statement labeled line 1 assigns he values 5, 6 and 4 to the variables z, x and y
respectively
The statement labeled line 2 increments the value of the variable x by 4
The statement labeled line 3 increments the value of the variable y by 5.

Operators

Operators are symbols that tells the compiler to perform specific mathematical or logic
manipulations

The Four Operator Classes are

1. Arithmetic
2. Relational
3. Logical
4. Bitwise

Arithmetic Operators

Unary and binary operators


+ unary or binary plus
- unary or binary minus
* multiplication
/ division
% modulus operator

Precedence of Operators

() Parenthesis highest
*, /, % Multiplication, Division, Modulus whichever comes first
from left to right if any to
+, - Addition, Subtraction whichever comes first from left
to right if any. lowest
Refer to the following example

1. ( 5 + 4)* 3 Operators inside the parenthesis are evaluated first

9 * 3=27

2. 5 + 4 * 3 Multiplication has a higher precedence than addition

5 + 12 = 17

Modulus Operator

The modulus operator is denoted by a percent sign (%). It returns the integer remainder
of two integer operands. Refer to the given example

int a, b, c;
a = 8;
b = 3;
c = a % b; //line1 c = 2
c = b % a; //line2 c = 3
The statement labeled line1 assigns the integer value 2 to the variable c since the
remainder is 2 when 8 is divided by 3.

The statement labeled line2 assigns the integer value 3 to the variable c since the
remainder is 3 when 3 is divided by 8.

In C, a mathematical expression should be a combination of an operand operator and an


operand. The following shows algebraic expressions and its equivalent in C.

Algebraic Expression Equivalent Algebraic Expression in C

abc a*b*c
a + bc a+b*c
y3 y*y*y
a a / (b+c)
(b+c)
a (a+b) a * (a+b)

C provides special assignment operators that make possible a more concise notation of
statements. Statement of the form variable op = expression is an alternate way of writing the
statement variable = variable op (expression ; Refer to the example below:

variable = variable op expression; variable op = expression;

sum = sum + 1; sum + = 1;


difff = diff – 1; diff - = 1;
prod = prod * ctr; prod * = ctr;
quo = quo/den; quo / = den;

Increment and Decrement Operators

++a pre-increment – the value of a after it is incremented


a++ post-increment – the value of a before it is incremented
--a pre-decrement – the value of a after it is decremented
a-- post-decremented – the value of a before it is decremented

Example

Statements Explanation

a = 5; c = 0; c = 6 and a = 6
c = ++a;

a = 5; c = 0; c = 5 and a =6
c = a++;

b = 3; c = 0; c = 2 and b = 2
c = --b;

b = 3; c = 0; c = 3 and b = 2
c = b--;

Relational Operators

Relational Operators Meaning Example


> Greater than x>y
>= Greater than or equal to x >= y
< Less than x<y
<= Lesser than or equal to x <= y
== Equals x == y
!= Not equal to x != y

Logical Operators

&& AND
|| OR
! NOT
Note:
The logical operators AND and OR take precedence to the relational operators. The logical
NOT, however, takes a higher precedence than anything.

As with relational operators, any expression involving a logical test will return either true
(1) or false (0) value.

Logical OR ( || )
Logical Logical Logical Expression1 OR Logical Result
Expression1 Expression2 Expression2
False(0) False(0) False || False 0 || 0 False (0)
False(0) True(1) False || True 0 || 1 True(1)
True(1) False(0) True || False 1 || 0 True(1)
True(1) True(1) True || True 1 || 1 True(1)

Logical OR is denoted by || (double pipe sign). Notice that based on the table, if one
logical expression is true the result is also true.

Example:

Assume the value of x is 6 and y is 8.

Expression Explanation Value

x >= 4 || y <= 5 True || False True (1)


y >= 9 || x < 4 False || False False (0)

Logical AND (&&)


Logical Logical Logical Expression1 AND Logical Result
Expression1 Expression2 Expression2
False (0) False (0) False && False 0 && 0 False (0)
False (0) True (1) False && True 0 && 1 False (0)
True (1) False (0) True && False 1 && 0 False (0)
True (1) True (1) True && True 1 && 1 True (1)

Logical AND is denoted by && (double ampersand sign). Notice that based on the table,
if one logical expression is false the result is also false.

Example:

Assume the value of x is 6 and y is 8.

Expression Explanation Value

x>=4 && y>=5 True && True True (1)


y>=9 && x<4 False && False False (0)

Logical NOT (!)


Logical Expression ! (Logical Expression) Result
False ! (False) True
True ! (True) False

Logical NOT negates the logical expression. Negating a true expression gives a false
value and negating a false expression gives a true value. Consider the example shown below.

Assume the value of x is 5 and y is 4

Expression Explanation Value

! (x>5) not(False) True (1)


!(y<=4) not(True) False (0)

Bitwise Operators
& Binary operator AND

Example:
int a = 3, b = 5, c;
c = a & b; // c = 1 0011 & 0101 = 0001

| Binary operator OR
int a = 3, b = 5, c;
c = a|& b; // c =7 0011 & 0101 = 0111

^ Exclusive OR
int a = 3, b =5, c;
c = a & b; // c = 7 0011 & 0101 = 0110

~ One’s Complement Operator


int a = 4, b;
b = ~ a; // a is 0100 b is 1011

Shift Operators
<<Shift Left
int a = 4,b;
b = a<<1; // a is 0100 b is 1000
>>Shift Right
int a = 4,b;
b = a>>2; // a is 0100 b is 0001

Order of Precedence

It is necessary to be careful of the meaning of such expressions as a + b * c. We may


want the effect as either (a + b) * c or a + (b * c). All operators have a priority, and high priority
operators are evaluated before lower priority ones. Operators of the same priority are evaluated
from left to right, so that a – b – c is evaluated as (a - b) – c as you would expect.

From high priority to low priority the order for some C operators is:
() &&
!, ,-,*,&,++,- ||
*,/,% ?:
+,- =, + =, - =
<, <=,>=,>
==,!=
&
,|
Student’s Name: Year/Section:
Instructor’s Name: Date:

____Chapter 3____
EXERCISE 1

1. Determine the data type of the following

a. 5.78 = _____________________________
b. -9 = _____________________________
c. 8.904 = _____________________________
d. ‘u’ = _____________________________
e. 898 = _____________________________

2. Determine the output of the following program fragments:

a. printf (“ I love C programming ”);

Output:
____________________________________________________________________________
______________________________________________________________________
__________

b. printf (“ The sum of 5 and 4 is % d and their product is %d”,


5 + 4, 5 * 4);

Output:
____________________________________________________________________________
______________________________________________________________________
__________

c. a = 5 ; b = 4 ; c = 8;

printf(“\n a = %d b = %d c = %d”, a, b, c);


printf(“\n the sum of %d and %d is %d”, a, b, a+b);
printf(“\n the product of %d and %d is %d”, a, b, a*b);

printf(“\n 25 mod 3 is %d”, 25 % 3);


printf(“\n 39 mod 4 is %d”, 39 % 4);

printf(“\n the mathematical expression 8 + 2 * 9 / 3 is %d”,


8 + 2 * 9 / 3);

printf(“\n the mathematical expression 9 * 4 + 10 / 2 is %d”,


9 * 4 + 10 / 2);

Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________________________________

d. printf(“ I love C programming \n I love C programming \n I


love Computer Programming”);

Output:
____________________________________________________________________________
______________________________________________________________________
__________

e. a = 5 ; b = 4 ; c = 8;

printf(“\n The value of 5 is %7d \n and the value of b is


%4.2d”, a, b);

printf(“\n The value of c is %3d”, c);

Output:
____________________________________________________________________________
______________________________________________________________________
__________

3. Convert the following algebraic expression to its equivalent mathematical expression in


C
a. abc + def = ______________________________
b. a( bc + ab ( c+d )) = ______________________________
c. k + (a+b) = ______________________________
y+q

4. Evaluate the following logical expressions. Supposed a = 5, b =7, c = 8. Which of the


following numbers return true values and false values?

A. a>=5 && b>6 || c<4 = ______________________________


B. c<4 || a>=5 && b>6 = ______________________________
C. a+b >= c*a && c>b !! b<=a = ______________________________
D. ! (b>6) = ______________________________
E. ! (b>6 && a <6) = ______________________________

5. What is printed in the following program fragment?

a = 6;
b = 7;

printf(“ the value is %d”, a++);


printf(“ the value is %d”, a);
printf(“ the value is %d”, a--);
printf(“ the value is %d”, a--);
printf(“ the value is %d”, b++);

c = a++ + b --;
printf(“ the value is %d”, c);
printf(“ the value is %d”, a);
printf(“ the value is %d”, b);

Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______

Student’s Name: Year/Section:


Instructor’s Name: Date:

____Chapter 3____
LABORATORY EXERCISE 1

1. Create a program that will display the following:


a. **********
**********
**********
**********
**********
b. 1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1

c. printf(“Hello World”);
d. scanf(“%d”, &value);
e. \\\Hello!, How are you?? “I’m fine!”//

2. Create a program that will input two (2) numbers and display the sum, product,
difference and quotient.
3. Create a program that will compute and display the area and circumference of a circle.
Note:
area = pi * r * r
circumference = 2 * pi * r

4. Create a program that will compute and display the area and perimeter of a rectangle.
Note:
area = length * width
perimeter = 2 (length + width)

5. Create a program that will input a number in feet, convert and display the number in
inches.

6. Create a program that will ask the user to input a number in feet and display the number
in yards.

7. Create a program that will ask the user to enter student’s prelim, midterm and finals
grade and will automatically display the average grade of the student.

Chapter 4

SELECTION STATEMENTS

Selection statements executes a set of instructions only if a conditional expression is


true and skip them if it is false. There are two selection statements in C. They are the following:

a. if statement
b. switch statement

The if statement

The flowchart below illustrates how the if statement works. It performs an action if the
conditional expression is true or skips the action if the conditional expression is false. The if
statement requires the use of parenthesis around the conditional expression. There is no
semicolon after the parenthesis and after the end of the curly brace. This limits the range of
actions subject to the conditional expression. The else part is optional. It may or may not be
included in an if statement. An example is given by the program if_c.c Notice that there is no
else part in the if statement.

The syntax of the if statement


is:

Conditional False if(conditional expression)


Expression {
Body of if…
}
else
True Body of else {
Body of else…
Body of if }

Exit

/* if_c.c: a program that demonstrates if statement */


#include<stdio.h>
void main()
{
int num = 0;
printf(“Please type in a number”);
scanf(“%d”, &num);
if (num = = 789)
{
printf(“Correct”);
}
}

The Else Statement

The else keyword is optional and is used when there are two possible courses of action
after an if statement. The first course of action is taken if the test is found to be true, else the
second of action is taken if the test is found to be false. An example is given by the program
if_else.c.

/* if_else.c: a program that demonstrates the if/else statement


*/

#include<stdio.h>

void main()
{
int num;

printf(“Please type in a number”);


scanf(“%d”, &num);
if(num = =789)
{
printf(“Correct”);
}
else
{
printf(“Incorrect”);
}
}

Note:
The body of the selection statements are contained in curly braces. If there is only one
statement associated with the conditional expression then there is no requirement for the
curly braces, but it is not a good programming practice.

The if else-if Construct (multiple alternatives)

It is also possible to construct an if else if construct (multiple alternatives). The syntax


is:

if (conditional expression1)
{
statement1;
statementn;
}
else if (conditional expression2)
{
statement1;
statementn;
}
.
.
else
{
statement1;
statementn;
}

The conditional expressions are evaluated from top to bottom. Once a true condition is
found, the statement associated with it is executed and the rest of the statements are bypassed.
If none of the conditions are true then the final else is executed. Let us all recall that the else
part is optional. Thus, if the else part is not present then, no action takes place if all other
conditions are false. The program if else.c evaluates the integer grade using the if..else if
construct.

/* if_else.c: a program that demonstrates the if else if construct


*/

#include<stdio.h>

void main ()
{
int grade;
float numgrade;
scanf(“%d”, &grade);
if (grade >= 100)
{
printf(“Excellent”);
numgrade = 4.0;
}
else if (grade >= 95)
{
printf(“Superior”);
numgrade = 3.5;
}
else if (grade >= 90)
{
printf(“Very Good”);
numgrade = 3.0;
}
else if (grade >= 85)
{
printf(“Good”);
numgrade = 2.5;
}
else if (grade >= 80)
{
printf(“Satisfactory”);
numgrade = 2.0;
}
else if (grade >= 75)
{
printf(“Passed”);
numgrade = 1.5;
}
else
{
printf(“Failed”);
numgrade = 0.0;
}
}

Using Logical And (&&)

Another variant of the program ifelse.c is the program ifand.c. The Logical operator
AND tests the range of values for grade.

/* ifand.c: a program that demonstrates the logical and */

#include<stdio.h>

void main ()
{
int grade;
float numgrade;
scanf(“%d”, &grade);
if (grade >= 75 && grade <=79)
{
printf(“Passed”);
numgrade = 1.5;
}
else if (grade >= 90 && grade <= 94)
{
printf(“Very Good”);
numgrade = 3.0;
}
else if (grade >= 95 && grade <= 99)
{
printf(“Superior”);
numgrade = 3.5;
}
else if (grade >= 85 && grade <= 89)
{
printf(“Good”);
numgrade = 2.5;
}
else if (grade >= 80 && grade <=84)
{
printf(“Satisfactory”);
numgrade = 2.0;
}
else if (grade > 100)
{
printf(“Excellent”);
numgrade = 4.0;
}
else
{
printf(“Failed”);
numgrade = 0.0;
}

Using Logical Or (||)

The program ifor.c uses the logical operator || to determine if the input marital code is an
uppercase or a lowercase.

/* ifor.c: program that demonstrates logical or */

#include<stdio.h>

void main ()
{
char marital_code;
scanf(“%c”, &marital_code);
if(marital_code == ‘M’ || marital_code == ‘m’)
printf(“Married”);
else if(marital_code == ‘S’ || marital_code == ‘s’)
printf(“Single”);
else if(marital_code == ‘D’ || marital_code == ‘d’)
printf(“Divorced”);
else if(marital_code == ‘W’ || marital_code == ‘w’)
printf(“Widowed”);
else
printf(“invalid code”);
}
The string functions toupper or tolower can be used instead of the logical operator OR.
String functions are discussed in Chapter 6.

The switch Statement

One of the problems with multiple if-else-if constructs is that they become unwieldy to
use and difficult to read. To avoid this problem the switch statement exists. It is, in effect, a
series of if statements nested into one construct. The flowchart below illustrates how the switch
statement works.

true
Variable = constant1 First case body

false

true
Variable = constant2 Second case body

false

The syntax of the switch statement is


exit
switch (variable)
{
case constant 1: {
…………action;
…………action; /* First Case */
break;}
case constant 2: {
…………action;
…………action; /* Second Case */
break; }
default: {
…………action;
…………action; } /* Default Case */
}
There are several key points relating to the switch statement:

 Where the if statement can test for relational or logical expressions, the switch statement
can only test for equality. The constant1, constant2, etc must be exact matches to the
expression in parenthesis (usually a variable).

 The inside of the curly braces will consist of blocks of code that specify actions if the
constant is matched. These blocks of code are given a label which consists of:

The case keyword, the constant or constant expression and a colon.

 No one label can have the same constant as another.

 Any action to be taken is coded after the label.

 The default keyword specifies what action is taken if no match is found. The label is
optional; no action will be taken at all if no match is found and the default is missing.

 The switch statement will progress through all available actions once the constant has
been matched. for this reason the break keyword prevents the switch statement from
performing actions unrelated to that particular constant.

 Where the actions to be processed are applicable to more than one constant, then it is
possible to have more than one label above these actions. However, each label must
follow the format specified above.

The program switcha.c uses the switch construct to determine the value of the
marital_code found in the program ifor.c.

/* switch.c : a program that demonstrates the switch statement */

#include<stdio.h>

void main ()
{
char marital_code;
scanf(“%c”, &marital_code);

switch(marital_code)
{
case ‘M’:
case ‘m’: printf(“Married”);
break;
case ‘S’:
case ‘s’: printf(“Single”);
break;
case ‘D’:
case ‘d’: printf(“Divorced”);
break;
case ‘W’:
case ‘w’: printf(“Widowed”);
default : printf(“invalid code”);
break;
}
}

Another example of the switch construct is the program switch.c

/* switch.c */

#include<stdio.h>
void main ()
{
int num;

printf(“Please type in a number”);


scanf(“%d”, &num);
switch(num)
{
case 1:
case 2:
printf(“One or Two \n”);
break;

case 3:
case 4:
printf(“Three or Four \n”);
break;

case 5:
case 6:
printf(“Five or Six \n”);

case 7:
case 8:
printf(“Bigger than Four \n”);
break;
default:
printf(“Invalid Number \n”);
break;
}
}
In the example, the user is asked to input a number. If the number is 1, 2, 3, or 4 then
the program will say either “One or Two” or “Three or Four”. The break statements will then
make the program jump to the end of the switch statement and move on with the processing.

If the user types a 5 or 6, the first constant to match is case 5 or case 6. This will cause
the program to print out “Five or Six”. However, as there are no break statement, the program
will continue through the next actions and print “Bigger than Four.

If a 7 or 8 typed then the program will simply state “Bigger than Four”.

If any other number is typed then the default option is chosen which prints “Invalid
Number”.

The ? (ternary) operator

The ? (ternary condition) operator is a more efficient form for expressing simple if
statements. It has the following form:

expression1 ? expression2 : expression3

It simply states that:

if expression1 then expression2 else expression3

For example to assign the minimum of a and b to z:

z=(a<b) ? a : b;

which is the same as:

if(a<b)
z = a;
else
z = b;

Suppose you want to print the string Even if the number is divisible by 2 otherwise print
Odd. Using the ternary condition operator the statement is

(num % 2 = = 0) ? printf(“Even”): printf(“Odd”);

which is the same as:

if(num % 2 = = 0)
printf(“Even”);
else
printf(“Odd”);
Student’s Name: Year/Section:
Instructor’s Name: Date:

____Chapter 4____
EXERCISE 1
Determine the output of the following program fragments

1. x = 3;
y = 5;
if ( x < 2 )
printf(“%d”,x);
else
printf(“%d”,y);

Output:
____________________________________________________________________________
______________________________________________________________________
__________

2. x = 4;
y = 5;
if ( x==4 )
printf(“%d”,x);
else
printf(“%d”,y);

Output:
____________________________________________________________________________
______________________________________________________________________
__________

3. status = 4;
if(status == 3)
{
printf(“Chemist\n”);
if(status == 4)
printf(“Physicist\n”);
else
printf(“Botanist\n”);
}
else
printf(“Biologist\n”);

Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________
4. x = 5;
if ( x < 6)
printf(“%d”, x);
else if ( x < 7 )
printf(“%d”, 2 * x);
else if ( x < 8 )
printf(“%d”, 3 * x);
else
printf(“%d”, 4 * x);

Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________

5. value = 1;
switch (value)
{
case 0: printf(“Red\n”);
break;
case 1:printf(“Yellow\n”);
break;
case 2:printf(“Pink\n”);
break;
}
printf(“End of switch”);

Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________

6. value = 1;
switch(value)
{
case 0: printf(“Red\n”);
case 1:printf(“Yellow\n”);
case 2:printf(“Pink\n”);
}
printf(“End of switch”);

Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________

Student’s Name: Year/Section:


Instructor’s Name: Date:

____Chapter 4____
EXERCISE 2
___________ 1. Which condition determines whether the value of the score variable is between
90 and 100 inclusive?

a. if(score>=90 && score <=100)


b. if(score>=’90’ && score <=’100’)
c. if(score>=90||score<=100)
d. if(score>=90 And score <=100)

___________ 2. For the compound condition to be true when the Or operator is being used,
the______.

a. condition 1 must be true


b. condition 2 must be true
c. condition 1 and condition 2 must be true
d. either condition 1 or condition 2 must be true

___________ 3. The compound condition ( 5 * 3 < 8 ||false) evaluates to?

a. False
b. True
c. No value
d. 0 or false value

___________ 4. For the compound condition to be true when the And operator is being used,
the______.

a. condition 1 must be true


b. condition 2 must be true
c. condition 1 and condition 2 must be true
d. either condition 1 or condition 2 must be true
___________ 5. The statement if (age >= 50) evaluates to ____ if the age variable contains the
number 50.

a. 50
b. True
c. Yes
d. t

Student’s Name: Year/Section:


Instructor’s Name: Date:

____Chapter 4____
LABORATORY EXERCISE

1. Create a program that will input three (3) numbers and display the highest number.
(Assume no equal values).

2. Create a program that will input a number and display “even” if the number is an even
number and “odd” if the number is an odd number.

3. Create a program that will input a number and will print “Divisible” if the number is
divisible by 5, otherwise print “Not Divisible”.

4. Create a program that will ask the user to input a character “m” or “f” and will display
“Hello Sir” if the input is “m” otherwise “Hello Madam”.

5. Create a program that will input grade and will display “Passed” if the grade is 75 or
higher, otherwise it will display “Failed”.

6. Create a program that will ask the user to input student’s Prelim, Midterm and Final
grade. After accepting the input, the program should automatically compute for its Final
Subject Grade and display the grade and its equivalent.

Formula:

Subject Grade = Prelim + Midterm + (Finals x 2)


4

Grade Equivalence:

96-100 = 1.00
94-95 = 1.25
92-93 = 1.50
89-91 = 1.75
87-88 = 2.00
84-86 = 2.25
80-83 = 2.50
78-79 = 2.75
75-77 = 3.00
Below 75 = 5.00

Chapter 5

REPETITIVE STATEMENTS

There are three iterative/repetitive statements in C. They are the following:


 for
 while
 do

The for Statement

The for loop is the most powerful and flexible of all of the loops used in C. The flowchart
below illustrates how the for statement works.

initialization expression

false
Conditional exit

true

Body of loop

increment/decrement expression

The general syntax is:

for (initialization; conditional expression; increment/decrement expression)


{
statement1;
statement2; /* Body of Loop */

.
.
statement n;
}

Note:
The body of loop or all iterative/repetitive statements are contained in curly braces. If there is only
one statement then of
An example there
theisuse
no of
requirement
for loop isforshown
the curly braces,
in the but it for1.c
program is not ausing
good an
programming
increment
practice.
expression.

/* for1.c: A program that demonstrates for loop with increment


expression. */
#include<stdio.h>

void main()
{
int num;
initialization Conditional expression Increment expression

for ( num = 0; num <= 5; num += 1; )


{
printf(“Count is %d\n”, num); /* body of the loop
executes 6 times */
/* from 0 to 5 */
}
}

Output:
Count is 0
Count is 1
Count is 2
Count is 3
Count is 4
Count is 5

Another example of a for loop is shown in the program for2.c using a decrement
expression.

/* for2.c: A program that demonstrates for loop with decrement


expression. */
#include<stdio.h>

void main()
{
int num;
initialization Conditional expression Increment expression

for ( num = 5; num >= 0; num -= 1; )


{
printf(“Count is %d\n”, num);
}
}
Output:
Count is 5
Count is 4
Count is 3
Count is 2
Count is 1
Count is 0

Infinite Loop

It is possible to omit any element within the parenthesis provided the semicolon is
retained. For example,

for( ; ; )
{
printf(“This loop runs forever\n”);
}

The for loop shown above causes an infinite loop. That is, a loop that runs forever.

It is, therefore, important that the initialization, conditional expression and


increment/decrement expression are performed somewhere in the program. Finally, it is
possible to have more than one initialization or loop control statement. These must be comma
separated:

for(a=0, b=10 ; a<10 && b>0 ; a++, b--)


{
printf(“%d is a, %d is b, \n”, a, b);
}

Note that there is still only one conditional test. Although it may be a compound test of
more than one piece of logic, it will always equate to true (1) or false (0).

The While Statement

The syntax of the while statement is:

while (conditional expression)


{
statement1;
statement2; /* Body of Loop */
statementn;
}

The flowchart below illustrates how the while statement works.

false
Conditional expression exit

true

Body of loop
In order that the loop body is executed the conditional expression should equate to true
(i.e.: 1).

Note that there is no semicolon after the conditional expression, but each independent
action within the body does.

An example of a while loop is shown in the program while1.c

Note that the variable num is initialized to zero when it is declared. The conditional
expression is that num is less or equal to five. It is also important that the body of the loop
contains an increment/decrement expression. In this case, the increment is the special
assignment operator +=.
Without the increment, the conditional expression would never be false and the loop
would continue forever.

/* while1.c: A program that demonstrates the while loop. */

#include<stdio.h>
void main()
{
int num = 0; initialization

while(num <= 5) conditional expression


{
printf(“Count is %d\n”, num);

num += 1; increment expression


}
}

Output
Count is 0
Count is 1
Count is 2
Count is 3
Count is 4
Count is 5
Output
Count is 0
Count is 1
Count is 2

The for loop is semantically equivalent to

initialization;
while (conditional expression)
{
statement1;
statement2;
increment/decrement expression;
}
The program while2.c demonstrates an equivalent while statement of the for statement
shown in the program for2.c

/* while2.c : A program that demonstrates an equivalent while statement


of the for statement shown in the program for2.c */

#include<stdio.h>
void main()
{
int num = 5; initialization

while(num >= 0) conditional expression


{
printf(“Count is %d\n”, num);

num -= 1; decrement expression


}
}

The do Statement

The do statement is different from the while statement. The body of the loop is
performed once before the conditional expression is tested. Thus, it executes the body of the
loop at least once. The flowchart below illustrates how the do statement works.

Body of loop

false
conditional exit

true

The general syntax of the do while loop is:

do
{
statement1;
statement2; /* Body of loop */


statementn;
}while(conditional expression);

For this particular loop the semicolon is required after the conditional expression. An
example of the use of the loop is shown in the program do.c. The loop, in this case, has exactly
the same effects as the while loop given by the program while.c.

/* do.c : A program that demonstrates the do loop. */


#include<stdio.h>
void main()
{
int num = 0;
do
{
printf(“Count is %d\n”, num);
num += 1;
}while(num <= 5);
}
Output
Count is 0
Count is 1
Count is 2
Count is 3
Count is 4
Count is 5

Nested Loop

The body of loop may include another loop. In this case, the loops are said to be nested.
The program nested.c contains a nested loop. The outer loop counts from 1 to 5 and the inner
loop counts from 1 to 4.

/*nested.c : A program that demonstrates a nested loop */

#include<stdio.h>
int ctr1, ctr2;
main()
{
Outer loop for (ctr1 = 1; ctr1 <= 5; ctr1++)
{
Inner loop for (ctr2 = 1; ctr2 <= 4; ctr2++)
{
printf(“outer loop count -> %d”, ctr1);
printf(“inner loop count -> %d\n”, ctr2);
}
}
}

The break Keyword

The break keyword can also be used as a means of control within a loop. It is often used
as
the loop control mechanism in a forever loop. The important thing to note is that it will only
break out of the current loop, so any nested loops will break to only one level higher. An
example is shown in the program break.c.

/* break.c : A program that demonstrates the use of the break mechanism */

#include<stdio.h>
void main()
{
int num;
for( ; ; )
{
printf(“Please type in a number”);
scanf(“%d”, &num);

if(num = = 521)
{
break;
}
}
printf(“Finished Looping”);
}

Once the break statement is reached, the loop is exited and the processing continues
with
the “Finished Looping” statement.

The continue Keyword

This key word is used to exit the current iteration of the loop, but continue with the next
loop control statement (i.e.: increment). An example of this is seen in the program continue.c,
where any user who is under eighteen will not be asked the subsequent questions. However,
the program will still run through ten iterations.

/* continue.c : A program that demonstrates the use of continue */

#include<stdio.h>
void main()
{
int num = 0, age;
char answer[15];
for(num = 0 ; num <= 10 ; num++)
{
printf(“Next person: please type in your age”);
scanf(“%d”, &age);
if(age < 18)
{
continue;
}
printf(“Do you drink coffee? \n”);
scanf(“%s”, answer);
}
printf(“Finished Looping”);
}

Student’s Name: Year/Section:


Instructor’s Name: Date:
____Chapter 5____
EXERCISE 1

Determine the output of the following program fragments:

1. for ( j=1; j<=5 ; j++ )


{
printf(“%d\n”, j);
}
printf(“%d\n”, j);

Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________

2. for ( j=1 ; j<=5 ; j++ ) {


printf(“%d\n”, j);
printf(“%d\n”, j); }

Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________

3. x = 8;
while(x >= 0)
{
printf(“%d\n”, x);
x = x-2;
}

Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________________

4. x = 8;
while ( x >= 0 )
{
x = x-2;
}
printf(“%d\n”, x);

Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________________

5. x = 2;
while ( x == 2 )
{
x = x – 1;
printf(“%d\n”, x);
}

Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________

6. x = 2;
while ( x == 2 )
{
x = x – 1;
}
printf(“%d\n”, x);

Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________

7. for ( x=1 ; x<=5 ; x++)


{
printf(“%d\n”, x);
if(x==3)
break;
printf(“bottom of loop”);
}
printf(“Out of loop\n”);

Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________________

8. for ( x=1 ; x<=3 ; x++)


{
printf(“%d\n”, x);
if( x==2 )
continue;
printf(“bottom of loop\n”);
}
printf(“Out of loop”);

Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________________

9. for ( ctr1=1 ; ctr1<=5 ; ctr1++)


{
for( ctr2=1 ; ctr2<=ctr1 ; ctr2++)
{
printf(“*”);
}
printf(“\n”);
}

Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________________

10. for ( ctr1=5 ; ctr1>=1 ; ctr1--)


{
for (ctr2=1 ; ctr2<=ctr1 ; ctr2++)
{
printf(“*”);
}
printf(“\n”);
}

Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________________
Student’s Name: Year/Section:
Instructor’s Name: Date:

____Chapter 5____
LABORATORY EXERCISE

1. Create a program that will print all odd numbers from 15 to 48.
2. Create a program that will input a starting number and an ending number and will print
all even numbers within the two numbers.
3. Create a program that will print all numbers divisible by five (5) starting from 257 down to
189.
4. Create a program that will print the following numbers: 120, 100, 80, 60, 40, 20.
5. Create a program that will print all prime numbers from 1 to 100.
6. Create a program that will display the sum of all numbers from 1 to 15.
7. Create a program that will display the following:

a. **********
**********
**********
**********
**********
b. *
**
***
****
*****
c. *
***
*****
*******
*********
d. 1
121
12321
1234321
123454321

8. Create a program that will display a Fibonacci series of numbers. The program should
ask the user to enter the size of the series and will automatically show the Fibonacci
series from 0 to the given size.
9. Create a program that will display a multiplication table of numbers. Starting from 1 to
10.
10. Create a program that will ask the user to input a starting number and ending number.
Based from the given range, display all odds, even and prime numbers.
Chapter 6

FUNCTIONS

Functions are used in modular programming. Functions are called in the void main
program and perform a specific task.

Advantages

 It fits naturally with the top-down design approach.


 It can be called more than once in a program
 It provides a natural method to divide a task among a team of programmers.
 It can be tested individually.

Characteristics

 A section of a program that performs a specific task. The task assigned to a function is
performed whenever C encounters the function name.

 Functions are the building blocks in a C program. Every C program has at least one
function and every executable C statement appears inside some function or another.

 As its simplest level a function performs a single task or operation. A computer program
generally consists of a series of tasks, each of which can be coded as a function and
called from the body of the program. In this way repetitive code is avoided.

Function Prototypes

C functions should be both declared and defined. A function declaration states the
return type, the function name, the parameter list it may take. This is known as function
prototype.

An example of a function prototype is

Return type Function name Parameter list

float compute_product (float x, float y);

A function definition actually creates the function and allocates the memory required.

Parts of a Function
1. Function header

a. Return Type
 Specifies the type of value that the function returns using the return
statement.
 If no type is specified, the function is assumed to return an integer result

b. Function name
 Identifier name for the function

c. Parameter list
 A comma-separated list of variables that receive the values of the arguments
when the function is called
 Also known as value parameters
 A function may or may not have parameters

2. Declaration section
 Local variable declaration

3. Function statements.

The General Form of a Function is:

return_type function_name (parameter_list)


{
declaration section
function statement1;
function statement2;
:
.
}

Note: The declarations for the standard C functions are contained in header files, while
the definitions are in the standard C library. Functions written by the programmer
should be declared at the beginning of the program and may be coded before or after
the void main() function.

Return Statement

 Causes an immediate exit of the function.


 Used to return a value.

Void Functions

Functions with no return values are called void functions. The program Func_a.c
contains the void function display that displays five asterisk.
/* Func_a.c demonstrates the function display that displays five
asterisks */

#include<stdio.h>
void display ( ); // function prototype
void main ( )
{
display ( ); //function call, execute function display
}
void display ( ) //function definition
{
int ctr; //local variable
for (ctr=1; ctr<=5; ctr++)
printf(“*”);
}

Output:
*****
Functions can be called more than once in a program. The program Func_b.c contains
the function display_asterisk. Notice that the function display_asterisk is inside the for loop.
This causes the function display_asterisk to execute five times.

/* Func_b.c : A program that demonstrates that a function can be


called more than once */

void display_asterisk ( ); //function prototype


void main ( )
{
int ctr;
for(ctr=1; ctr<=5; ctr++)
{
display_asterisk ( ) ; //function call
}

}
void display_asterisk ( ) //function definition
{
printf(“*”);
}

Functions with Return Values

The program fntn1.c contains the function compute_sum that accepts two integer
parameters a and b and returns the integer sum. It also contains the function
compute_product that accepts two float parameters c and d and then returns the product that
is of type float.
/* fntn1.c: A program that demonstrates the function compute_sum that
returns an integer value and compute_product that returns a float
value */
#include<stdio.h>

int compute_sum(int a, int b); //function prototypes


flaot compute_product(float c, float d);

void main()
{
printf(“the sum is %d”, compute_sum(8,9)); /*function call,
execute function */

printf(“the product is %f”, compute_product(3.5, 8.95));


}

int compute_sum(int a,int b)


{
return a + b;
}

float compute_product(float c, float d)


{
return c * d;
}

The program fntc2.c contains the function display_letter_grade that accepts an integer
parameter grade and returns the equivalent character grade.

Integer Grade Character Grade


95-100 A
91 – 94 B
86 – 90 C
80 - 85 D
75 – 79 E
0 – 74 F

/*fntn2.c: A program that demonstrates the function


display_letter_grade that returns a char value */

#include<stdio.h>
char display_letter_grade(int grade);
void main()
{
int grade;
scanf(“%d”, &grade);
printf(“%c”, display_letter_grade(grade));
}

char display_letter_grade(int grade)


{
if(grade >= 95) return ‘A’;
else if(grade >= 91) return ‘B’;
else if(grade >= 86) return ‘C’;
else if(grade >= 80) return ‘D’;
else if(grade >= 75) return ‘E’;
else return ‘F’;
}
Parameters are optional. If present in a function, they can be passed in two ways.
Pass by value and pass by reference.

Pass by Value

A copy of the arguments value is made and passed to the called function. Changes to
the copy do not affect the original variable’s value in the caller. It should be used whenever the
function does not need to modify the value of the original variable. The program swap_a.c
contains the function swap with two parameters a and b that are passed by value.

/* swap_a.c contains the function swap with two parameters a and b


that are passed by value */

#include<stdio.h>
void swap(int a, int b);
void main()
{
int a = 5, b = 10;
swap(a,b); //function call
printf(“In function void main\n”);
printf(“a = %d\n b = %d”, a,b);
}
void swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
printf(“In function swap\n”);
printf(“a = %d b = %d \n”, a,b);
}
Output:
In function swap
a = 10 b = 5
In function void main
a = 5 b = 10

Notice that the values of a and b in function void main did not change after the execution
of the function swap.

Passed by Reference

It allows the function to modify the original variable’s value. The program swap_b.c
contains the function swap and passed the parameters by reference. In passing by reference.
The address to the argument is copied to the parameter.
/* swap_b.c */

#include<stdio.h>
void swap (int *a, int *b);
void main()
{
int a = 5, int b = 10;
swap(&a, &b); /* pass the address of the parameters */
printf(“In function void main \n”);
printf(“a = %d \n b = %d”, a,b);
}
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
printf(“In function swap \n”);
printf(“a = %d b = %d \n”, a,b);
}
Output:
In function swap
a = 10 b = 5
In function void main
a = 10 b = 5

Global vs. Local Variable

1. Global variables are known throughout the entire program and may be used by any
piece of code.
2. Local variables are variables that are declared inside a function and may only be used
inside the function where it is declared.

The program variable.c demonstrates global and local variables.

/* variable.c : A program that demonstrates global and local variables


*/

#include<stdio.h>
int x = 20; Global Variable

void local_function();
void main()
{
printf(“the value of x in function void main is %d”, x);
local_function();
printf(“the value of x after the execution of local_function is
%d”, x);
}
void local_function()
{
int x = 5; Local Variable

printf(“the value of x in function local_function is %d”, x);


}

Student’s Name: Year/Section:


Instructor’s Name: Date:

____Chapter 6____
EXERCISE 1
1. What is printed?

int f( );
int g( );
void main()
{
int x,y,s;
s = 2;
y = f(s);
g = f(s);
z = f(s);
printf(“%d %d %d”, s,y,z);
}

int f (int a)
{
int t = 8;
a += 5;
t -= 4;
return (a + t);
}

int g (int a)
{
int t = 1;
a += 5;
t += a;
return (a + t);
}

Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________________________________________

2. What is printed?

float x = 4.5;
float f (int a);

void main()
{
float y;
x *= 2.0;
y = f(x);
printf(“%f %f \n”, x,y);
}

float f(float a)
{
a += 1.3;
x -= 4.8;
return (a + x);
}

Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________________________________________

3. Which of the following statements can be used to call a void function named printHead,
that accepts two integer parameters named title and grade?

a. void printHead(int title, int grade)


b. printHead(title, grade);
c. printHead void(title, grade);
d. printf(“%d”, printHead(title, grade));

4. Which of the following function prototypes can be used for a void function named
dispHead that will be passed the address of two integer variables name num1 and
num2.

a. void dispHead(num1, num2);


b. void dispHead(&num1, &num2);
c. void dispHead(num1&, num2&);
d. void dispHead(int &num1, int &num2);

Student’s Name: Year/Section:


Instructor’s Name: Date:

____Chapter 6____
LABORATORY EXERCISES
1. Write a function Oriented Program that converts the input inches into its equivalent
centimeters. One inch is equal to 2.4 cms. Display the converted centimeters value.

2. Write a function Oriented Program that calculates the area of a Circle. Use the formula: )
is equal to 3.1416 (approximately).

3. Write a function-oriented program that generates the Fibonacci series numbers of n (as
input) and display them. In Fibonacci, the current third number is the sum of two
previous numbers.

4. Write a function-oriented program that calculates the power value of the input base
number and exponent number. Then display the power value.

Sample Input/Output:

Enter base number: 5


Enter exponent number: 3
Power Value: 125

Chapter 7

ARRAY

A fixed number of data items which are stored contiguously and the elements can be
accessed by an index/subscript. It is also a finite ordered collection of homogenous elements.
Thus, the following are the characteristics of an array:
 Finite. There is a specific number of elements in the array.
 Ordered. All the elements of the array are arranged so that there is first, second, third
and so on.
 Homogeneous. All the elements in the array must be of the same type (e.g. all integers,
all characters, all floating point).

Two data types associated with an array

 Base type (component type) of the array


type of elements, or components of the array
 Index (subscript) type of the array
type of the values used to access the individual elements of the array.

There are 2 basic operations that are associated with an array:

 Extraction is an operation that accepts an array variable, indicated by its array name
and element of its index type and returns the array’s content

Example: X = b[3];
H = x[ctr1][ctr2];

 Storing is an operation that accepts a value and stores it in an array variable.

Example: A[4] = 4;
F[ctr] = ctr + 1;

Sample Declaration:

int array_int [10]; // array_int is an array of integers with


10 elements and whose subscript or index
ranges from 0 to 9.

char array_char [5]; // array_char is an array of characters


with 5 elements and whose subscript or
index ranges from 0 to 4.
One Dimensional Array

The program Array1.c contains three (one dimensional) arrays namely: array_int,
array_char and array_float. array_int has five elements which are integers, array_char has five
elements which are characters and array_float has five elements which are floats. The first for
loop stores integers, characters and float values to all the elements of the three arrays. The
second for loop displays the contents of all the elements of the three arrays. The first element of
an array has a subscript of 0, the second element has a subscript of 1, the third element has a
subscript of 2 and so on. Refer to the figure below.

/* Array1.c demonstrates one dimensional arrays */

#include<stdio.h> array_int[0] 2
void main() array_int[1] 3
array_int[2] 4
array_int[3] 5
array_int[4] 6
array_char[0]
‘a’
array_char[1]
array_char[2] ‘a’
array_char[3] ‘a’
‘a’
{
int array_int [5];
int array_char [5];
int array_float [5];
int ctr;

for (ctr=0; ctr<=4; ctr++)


{
array_int [ctr] = ctr + 2;
array_char [ctr] = ‘a’;
array_float [ctr] = 1.54;
}
}

The program Array2.c allows the user to store 10 integers, accumulate their sum and
extract (print) the integers in reverse order.

/* Array2.c : A program that demonstrates */

#include<stdio.h>
void main()
{
int array_int [10];
int ctr, sum;
sum = 0;

for (ctr = 0; ctr <= 9; ctr++)


{
scanf(“%d”, &array_int[ctr]);
sum += array_int[ctr];
}
for (ctr = 9; ctr >= 0; ctr--)
{
printf(“%d\n”, array_int[ctr]);
}
}
Two Dimensional Arrays

A two dimensional array has two pairs of square brackets. The statement int array_2d[2][3];
defines a two dimensional array of integers with 6 elements. To compute for the number of elements,
simply multiply the first dimension with the second dimension. In the declaration, simply multiply 2 by 3.
Two subscripts are needed to access each element. Refer to the figure below.

array_2d[0][0] array_2d[0][1] array_2d[0][2]


array_2d[1][0] array_2d[1][1] array_2d[1][2]

Examples of references to a two dimensional array:

array_2d [1] [2] = 5;


array_2d [0] [1] = array_2d[0] [1] + 2;
The program two_d.c stores the integer value 3 to all the elements of the two
dimensional array array_2d. A nested loop is used to access each element. The outer loop
counts from 0 to 1 because the subscript of the first dimension has values from 0 to 1. The inner
loop counts from 0 to 2 because the subscript of the second dimension has values from 0 to 2.

/* two_d.c: A program that demonstrates a two dimensional array */

#include<stdio.h> 3 3 3
void main() 3 3 3
{
int array_2d [2][3]; array_2d

int ctr1, ctr2;


for(ctr1=0; ctr1<=1; ctr1++)
{
for(ctr2=0; ctr2<=2; ctr++)
{
array_2d [ctr1] [ctr2] = 3;
}
}
}

Student’s Name: Year/Section:


Instructor’s Name: Date:

____Chapter 7____
EXERCISE 1

1. Consider the following array declarations:

int array_int [5];


float array_float [3][9];
char array_char [3][4][8];

a. How many elements does the following array contain?


Answer:___________________________________________________________________
b. What is the subscript of the third element of array_int?
Answer:___________________________________________________________________

c. How many subscripts are needed to access the elements of array_char?


Answer:___________________________________________________________________

d. How many subscripts are needed to access the elements of array_int?


Answer:___________________________________________________________________

e. An array_char can store what type of values?


Answer:___________________________________________________________________

f. An array_int can store what type of values?


Answer:___________________________________________________________________

2. Consider the following code. What is printed?

int array_1dim [5];


int x, y, ctr ;

x = 2; y = 3;
array_1dim[0] = 4;
array_1dim[1] = 3;
array_1dim[2] = 5;
array_1dim[3] = 7;
array_1dim[4] = 8;

printf(“\n %d”, array_1dim[3]);


array_1dim[x+2] = array_1dim[x];
printf(“\n %d”, array_1dim[array_1dim[0]]);
array_1dim[2] += 4;
printf(“\n %d”, array_1dim[2]);
for(ctr=0; ctr<=4; ctr++)
{
array_1dim[ctr] += 2;
}

for(ctr=0; ctr<=4; ctr++)


{
printf(“\n %d”, array_1dim[ctr]);
}

Output:
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
___________________________________________________________

Student’s Name: Year/Section:


Instructor’s Name: Date:

____Chapter 7____
LABORATORY EXERCISES

1. Create a program that stores integer values to an array whose size is 15. Futhermore,
increment by five the integers that are divisible by 3.

2. Create a program that stores 10 integers. Print the maximum and the minimum integer
found in the array.

3. Create a program that will ask the user to input 9 integer numbers and display its vertical
and horizontal sum. The numbers should be encoded in a 3 rows and 3 columns
manner. After the user entered each set of numbers in a row, the horizontal sum of the
set of numbers should automatically be shown.
Example:
5 10 15 = 30
Once all 3 set of numbers have been entered, the vertical sum should automatically be
displayed.

Example:
5 10 15 = 30
3 6 9 = 18
1 2 3 = 6
_____________________________
9 18 27 = 55

4. Create a program that will display magic square of numbers based on a given odd magic
square size. A magic square is a square array of numbers consisting of the distinct
positive integers 1,2, …, arranged such that the sum of the numbers in any horizontal,
vertical, or main diagonal line is always the same number, known as the magic constant.
The program should ask the user to enter an odd integer that will serve as the size of the
square. The program should validate if the entered number is an odd or even number. If
the number is even, the program should display an error message and ask the user to
enter a number again. Once a valid size is entered, the program should automatically
display the magic square.

Example:
Enter the size of the square: 3
The magic square of size 3 is:

6 1 8
7 5 3
2 9 4

You might also like