Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
220 views

MODULE in Computer Fundamentals

This module provides a comprehensive introduction to the ANSI C language, emphasizing portability and structured design. Students are introduced to all major language elements including fundamental data types, flow control, and standard function libraries. Thorough treatment is given to the topics of string and character manipulation, standard I/O, macro definition, and the C runtime library.

Uploaded by

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

MODULE in Computer Fundamentals

This module provides a comprehensive introduction to the ANSI C language, emphasizing portability and structured design. Students are introduced to all major language elements including fundamental data types, flow control, and standard function libraries. Thorough treatment is given to the topics of string and character manipulation, standard I/O, macro definition, and the C runtime library.

Uploaded by

Bry Camel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

University of Cebu

Expanded Tertiary Education Equivalency Accreditation Program


Bachelor of Science in Computer Engineering

MODULE 3

Computer Fundamentals
Programming 1

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 1


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

This module provides a comprehensive introduction to the ANSI C language,


emphasizing portability and structured design. Students are introduced to all
major language elements including fundamental data types, flow control, and
standard function libraries. Thorough treatment is given to the topics of string
and character manipulation, standard I/O, macro definition, and the C runtime
library. In this module you will learn more about Computer Ethics and Engineering Laws.
The module consists of ten short lessons:

❖ Lesson 1 – Programming Languages


❖ Lesson 2 – Algorithms
❖ Lesson 3 – Program Development Life Cycle
❖ Lesson 4 – Introduction to C
❖ Lesson 5 – C Fundamentals
❖ Lesson 6 – Operators and Expressions
❖ Lesson 7 – Data Input and Output
❖ Lesson 8 – Control Statements

After going through this module, you should be able to:

1. Understand the computer systems, program development cycle, basic analysis and
design techniques for computer programming.

2. Determine the elements of high-quality programs.

3. Describe the three basic structures – sequence, selection, and loop

4. Understand the advance modularization techniques.

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 2


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Please answer the following questions.

1. A computer assisted method for the recording and analyzing of existing or hypothetical
systems is
a. data transmission b. data flow c. data capture d. data processing

2. The brain of any computer system is


a. ALU b. Memory c. CPU d. Control Unit

3. Which of the following is the 1’s compelement of 10?


a. 01 b. 110 c. 11 d. 10

4. The binary system uses powers of


a. 2 b. 10 c. 8 d. 16

5. A computer program that converts assembly language to machine language is


a. compiler b. interpreter c. assembler d. comparator

6. The section of the CPU that selects, interprets and sees to the execution of program
instructions
a. memory b. register unit c. control unit d. ALU

7. The examination and changing of single bits or small groups of his within a word is called
a. bit b. byte c. bit manipulation d. bit slice

8. Which computer has been designed to be as compact as possible?


a. mini b. super computer c. micro comptuer d. mainframe

9. The 2’s complement of a binary no. is obtained by adding … to its 1’s complement.
a. 0 b. 1 c. 10 d. 12

10. ASCII stands for

a. American standard code for information interchange


b. All purpose scientific code for information interchange
c. American security code for information interchange
d. American scientific code for information interchange

11. Any storage device added to a computer beyond the immediately usable main storage is
known as
a. floppy disk b. hard disk c. backing storage d. punched card

12. The list of coded instruction is called


a. computer program b. algorithm c. flowchart d. utility programs

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 3


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Lesson 1 – Programming Languages


Computer needs a set of instructions to process data

A program is a sequence of instructions for a computer to perform

Software, for our purposes, is just a term meaning programs

What Kinds of Instructions?

- Input/Output (I/O)
- Arithmetic & logical calculation
- Decisions
- Repetitions

Some Key Terms

A programming language is a well-defined set of rules for specifying a program’s sequence of


instructions.

- Examples: C, C++, Fortran 90, Java, Basic, HTML, Perl, Haskell, Prolog, Pascal, etc.

Source code is a sequence of instructions, written in a human-readable programming language,


that constitute a program, or a piece of a program

A source file is a file of source code

A language is a system of communication

A programming language consists of all symbols, characters, and usage rules that permit
people to communicate with computers.

TYPES OF PROGRAMMING LANGUAGE

Even though all programming languages have an instruction set that permits these familiar
operations to be performed, there’s a marked difference to be found in the symbols, characters,
and syntax of them.

Programming languages are said to be lower or higher, depending on whether they are closer to
the language the computer itself uses (lower, which means 0s and 1s) or to the language that
people use (higher, which means more English like)

Programming Languages: Levels/Generations

- Machine Languages / First-generation languages


- Assembly Languages / Second-generation languages
- Procedural Languages / Third-generation languages
- Problem-oriented Languages / Fourth-generation languages
- Natural Languages / Fifth-generation languages

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 4


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

High Level Languages

High-level languages assist programmers by reducing the number of computer operation details
they have to specify, so that they can concentrate more on the logic needed to solve the problem.

High-level languages are often oriented toward a particular class of processing problems.

- For example, a number of languages have been designed to process scientific-mathematic


problems, and other languages have appeared that emphasize file processing application.

Unlike assembly programs, high-level language programs may be used with different makes of
computers with little modification.

- Thus reprogramming expense may be greatly reduced.

COMPILERS

Naturally, a source program written in a high-level language must also be translated into machine-
usable code.

There are two kinds of translators —compilers and interpreters — and high-level languages are
called either compiled languages or interpreted languages.

In a compiled language, a translation program, known as compiler, is run to convert the


programmer’s entire high-level program, which is called the source code, into a machine language
code. This translation process is called compilation.

The machine language code is called the object code and can be saved and either run (executed)
immediately or later.

INTERPRETERS

In an interpreted language, a translation program, known as interpreter, converts each program


statement into machine code just before the program statement is to be executed.

Translation and execution occur immediately, one after another, one statement at a time.

Unlike the compiled languages, no object code is stored and there is no compilation. This means
that in a program where one statement is executed several times (such reading an employee’s
payroll record), that statement is converted to machine language each time it is executed.

Compiled Vs Interpreted Languages

Compiled languages programs are better than interpreted languages programs as they can be
executed faster and more efficiently once the object code has been obtained.

On the other hand, interpreted languages programs do not generate object code and so are usually
easier to code and test.

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 5


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Lesson 2 – Algorithms
Problem Solving Process

System Design:

- Find a set of sub-problems such that


- each sub-problem is easy to solve; and
- the desired problem can be solved by solving them

Algorithm Design:

- Find solution to each sub-problem

Programming:

- Translate algorithms into codes

Computing problems

- Solved by executing a series of actions in a specific order

Algorithm is a procedure determining

- Actions to be executed
- Order to be executed
- Example: recipe

Program Control

- Specifies the order in which statements are executed

Algorithm: Definition

An algorithm is a precise specification of sequence of instructions to be carried out in order


to solve a given problem

- Each instruction tells what task is to be done


- Specification of a sequence of instructions to do a job is used in many fields

o A cooking recipe, The rules of how to play a game, VCR instructions, Description
of a martial arts technique, Directions for driving from A to B, A knitting pattern, A
car repair manual

A Wrong Algorithm

What is wrong with this so called algorithm?

- Directions: (From the back of a shampoo bottle.)


- Wet hair.
- Apply a small amount of shampoo, lather, rinse, repeat.

If you follow this algorithm, you will never finish washing your hair!

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 6


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Properties of Algorithms

Inputs:

- A number of quantities are provided to an algorithm initially before the algorithm begins.
These quantities are the inputs which are processed by the algorithm.

Definiteness:

- The processing rules specified in the algorithm must be precise, unambiguous and lead
to a specific action.

Effectiveness:

- Each instruction must be sufficiently basic such that it can, in principle, be carried out in a
finite time by a person with paper and pencil.

Finiteness:

- The total time to carry out all the steps in the algorithm must be finite. An algorithm may
contain instructions to repetitively carry out a group of instructions. This requirement
implies that the number repetitions must be finite.

Outputs:

- An algorithm must have one or more output

Correctness:

- Correct set of output must be produced from the set of inputs. For the same input data, it
must always produce the same output.

WRITING ALGORITHMS

There are various techniques that can be used to write algorithms:

- in English (e.g. enrollment guide)


- by diagrams (e.g. instructions for assembling kitset furnitures)
- by Flowcharts
- in pseudocode
- in a computer programming language
- in some other more-or-less formal language (e.g. knitting pattern)

A Simple Example

Fahrenheit to Celsius Conversion

- Step 1: Read the temperature in Fahrenheit from the keyboard


- Step 2: Calculate its Celsius equivalent as (F-32) X 5/9, where F is the inputted Fahrenheit
value
- Step 3: Print the calculated Celsius value on the screen

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 7


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Pseudocode

Pseudocodeis a written statement of an algorithm using a restricted and well-defined vocabulary.

It is, as the name suggests, cannot be executed on a real computer, but models and resembles
real programming code, and is written at roughly the same level of detail.

It is very much like a 3GL and is therefore more easily translated into programming language.

For many programmers and program designers is the preferred way to state algorithms and
program specifications.

No standard rules for writing.

Writing Algorithms in Pseudocode

Pseudocodecontains two main elements, the first being keywords.

These keywords often resemble programming commands and often occur as pairs of words.

- When writing a keyword in pseudocodewe would often write it in UPPERCASE and may
even highlight it using boldface.

The second element is that pseudocoderelies on indenting to show structure.

- This enables the person working with the algorithm to easily see the flow of logic through
the algorithm.

Example

Computing area of a rectangle

Input: length and breadth of the rectangle


Output: Area of the rectangle

Step 1. READ length


Step 2. READ breadth
Step 3. COMPUTE length * breadth GIVING area
Step 4. PRINT area

Values and Variables

Values

- Represent quantities, amounts or measurements.


- May be numerical or alphabetical (or other things)
- Often have a unit related to their purpose
- Example: Recipe ingredients

Variables

- Are containers for values


- places to store values

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 8


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Components of an Algorithm

Values and Variables

Instructions (a.k.a primitive)

- Some action that is simple and unambiguous

Sequence (of instructions)

- A series of instructions to be carried out one after the other

Selection (between instructions)

- An instruction that decides which of two possible sequences is executed


- The decision is based on a single true/false condition

Repition (of instructions)

- Repeat an instruction. while (or maybe until) some true or falsecondition occurs.
- Test the condition each time before repeating the instruction.

FLOWCHARTS

Graphical representation of an algorithm that illustrates the sequence of operations to be


performed using special-purpose symbols connected by arrows.

Flowcharts typically show a program’s logic.

Generally drawn in the early stages of formulating computer solution.

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.

FLOWCHART SYMBOLS

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 9


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

GUIDELINES

In drawing a proper flowchart, all necessary requirements should be listed out in logical order.

The flowchart should be clear, neat and easy to follow There should not be any room for
ambiguity in understanding the flowchart.

The usual direction of the flow of a procedure or system is from left to right or top to bottom.

Only one flow line should come out from a process symbol.

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.

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

Some rules for flowcharts

Every flow chart has a START symbol and a STOP symbol.

The flow of sequence is generally from the top of the page to the bottom of the page. This can
vary with loops which need to flow back to an entry point.

Use arrow-heads on connectors where flow direction may not be obvious.

There is only one flow chart per page.

A page should have a page number and a title.

A flow chart on one page should not break and jump to another page.

A flow chart should have no more than around 15 symbols (not including START and STOP).

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 10


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

SYSTEM FLOWCHART

System flowchart describes the data flow for a data processing system.

It provides a logical diagram of how the system operates. It represents the flow of documents, the
operations performed in data processing system.

It also reflects the relationship between inputs, processing and outputs.

Following are the features of system flowcharts:

- the sources from which data is generated and device used for this purpose.
- various processing steps involved.
- the intermediate and final output prepared and the devices used for their storage..

PROGRAM FLOWCHART

A program flowchart represents, in detail, the various steps to be performed within the system for
transforming the input into output.

The various steps are logical/ arithmetic operations, algorithms etc.

It serves as the basis for discussions and communication between the system analysts and the
programmers.

Program flowcharts are quite helpful to programmers in organizing their programming efforts.

These flowcharts constitute an important component of documentation for an application.

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 11


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Instructions: Read and understand each given item carefully. Write your final answer clearly and
neatly. No Erasure. Erasure made is considered wrong.

1. Compiler is used to find syntax error in

a. Executable file
b. Source file
c. Object file
d. Directory file

2. A program written in C language is stored in the

a. Source file
b. Executable file
c. Object file
d. Directory file

3. What are the three algorithm constructs?

4. What is the difference between a flowchart and pseudocode?

5. In a flowchart a calculation (process) is represented by

a. a rectangle
b. a rhombus
c. a parallelogram
d. a circle

6. A flowchart needs to represent the a situation where for each mark a student is award 'Pass'
or 'Fail'...the system will consider the mark and if it's 50 or over award 'Pass', else it awards
'Fail'. This is an example of which of the algorithm constructs?

a. decision
b. loop
c. sequence
d. all of the above

7. We can show the sequence of steps in an algorithm in a structural diagram called a flowchart.

a. True
b. False

8. What should be considered when designing an algorithm?

a. If the correct hardware is being used


b. If there is more than one way of solving the problem
c. If the correct software is being used

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 12


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

9. When can algorithms be used?

a. Only with computers


b. Only with flowcharts
c. Only when programming
d. Any time to design solutions to problems

10. A flowchart

a. Helps you plan out computer code


b. Uses shapes to help organize a process
c. Is a type of graphic diagram that represents an algorithm
d. All of the above

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 13


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Lesson 3 – Program Development Life Cycle


Program Development Life Cycle

Creating new programs is called program development.

The process associated with creating successful applications programs is called the program
development life cycle(PDLC).

It includes a set of activities which produce application programs.

There are various approaches in program development each with different perspectives.

Figure 1-1 illustrates the program development cycle, which can be broken down into at least
seven steps:

1. Understand the problem.


2. Plan the logic.
3. Code the program.
4. Use software (a compiler or interpreter) to translate the program in to machine language).
5. Test the program.
6. Put the program into production.
7. Maintain the program.

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 14


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Waterfall Model

The first published model of program development process was derived from other engineering
process (Royce, 1970).

It is a multistage model with each stage concerned with separate activities of program
development.

Each stage in the model follows a linear sequence one after another, often with feedback loops.

Also known as classic life cycle, linear sequential model.

UNDERSTANDING THE PROBLEM

Professional computer programmers write programs to satisfy the needs of others, called users
or end users.

Examples of end users include a HR Dept. that needs a printed list of all employees.

A Billing Dept. that wants a list of clients who are 30 or more days overdue on their payments,
and an

Order Dept. that needs a website to provide buyers with an online shopping cart.

Because programmers are providing a service to these users, programmers must first understand
what the users want.

When a program runs, you usually think of the logic as a cycle of input-processing-output
operations, but when you plan a program, you think of the output first.

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 15


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

In summary, understanding the problem consist of the following tasks:

- Define Objectives of the Program


- Determine desired outputs
- Determine input requirements
- Determine processing requirements
- Evaluate feasibility of the program
- Document the analysis

PLANNING THE LOGIC

The heart of the programming process lies in planning the program’s logic.

During this phase of the process, the programmer plans the steps of the program, deciding what
steps to include and how to order them.

You can plan the solution to a problem in many ways.

Two common planning tools are flowcharts and pseudocode; you will work with many examples
of flowcharts and pseudocode in this course.

You may hear programmers refer to planning a program as “developing an algorithm”.

An algorithm is the sequence of steps or rules you follow to solve a problem.

The programmer shouldn’t worry about the syntax of any particular language during the planning
stage, but should focus on figuring out what sequence of events will lead from the available input
to the desired output.

Planning the logic includes thinking carefully about all the possible data values a program might
encounter and how you want the program to handle each scenario.

Complete Program Design Tools

- Structure charts
- Flowcharts
- Pseudocode
- Data modeling

The process of walking through a program’s logic on paper before you actually write the program
is called desk-checking.

Structure charts – depict the overall organization of a program, and how the modules of a
program – logically related operations that perform a well-defined task – are defined and how
they connect to each other hierarchically.

Program modules should be arranged hierarchically, in a top-down fashion, so that their


relationship to each other is apparent.

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 16


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

CODING THE PROGRAM

The programmer can write the source code for a program only after the logic is developed.

Programmers choose particular languages because some have built-in capabilities that make
them more efficient than others at handling certain types of operations.

Despite their differences, programming languages are quite alike in their basic capabilities – each
can handle input operations, arithmetic processing, output operations, and other standard
functions.

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 17


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Only after choosing a language must the programmer be concerned with proper punctuation and
the correct spelling of commands – in other words, using the correct syntax.

Some experienced programmers can successfully combine logic planning and program coding in
one step.

Which step is harder: planning the logic or coding the program?

USING SOFTWARE TO TRANSLATE THE PROGRAM INTO MACHINE LANGUAGE

Even though there are many programming languages, each computer knows only one language
– its machine language, which consists of 1s and 0s.

From High-level programming language it must be converted to low-level machine language


that the computer understands.

TESTING THE PROGRAM

A program that is free of syntax errors in not necessarily free logical errors.

A logical error results when you see a syntactically correct statement but use the wrong one for
the current context.

For example, the English sentence The dog chases the cat, although syntactically perfect, is not
logically correct if the dog chases a ball or the cat is the aggressor.

After a program is free of syntax errors, the programmer can test it-that is, execute it with some
sample data to see whether the results are logically correct.

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 18


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Recall the number-doubling program:

If you execute the program, provide the value 2 as input to the program, and the answer 4 is
displayed, you have executed one successful test run of the program.

However, if the answer 40 is displayed, maybe the program contains a logical error.

Maybe the second line of code was mistyped with an extra zero.

The process of finding and correcting program errors is called debugging.

You debug a program by testing it using many sets of data.

For example, if you write the program to double a number, then enter 2 and get an output value of
4, that doesn’t necessarily mean you have a correct program.

Perhaps you have typed this program by mistake:

PUTTING THE PROGRAM INTO PRODUCTION

After the program is thoroughly tested and debugged, it is ready for the organization to use.

Putting the program into production might mean simply running the program once, if it was written
to satisfy a user’s request for a special list.

However, the process might take months if the program will be run on a regular basis, or if it is
one of a large system of programs being developed.

Perhaps data-entry people must be trained to prepare the input for the new program, users must
be trained to understand the output, or existing data in the company must be changed to an
entirely new format to accommodate this program.

Conversion, the entire set of actions an organization must take to switch over to using a new
program or set of programs, can sometimes take months or years to accomplish.

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 19


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

MAINTAINING THE PROGRAM

Maintenance can be required for many reasons: As examples

1. New tax rates are legislated, the format of an input file is altered, or the end user requires
additional information not included in the original output specifications.
2. New features will be added.

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 20


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Instructions: Read and understand each given item carefully. Write your final answer clearly and
neatly. No Erasure. Erasure made is considered wrong.

1. Which of the following pairs of steps in the programming process is in the correct order?

a. code the program, plan the logic


b. test the program, translate it into machine language
c. put the program into production, understand the problem
d. code the program, translate it into machine language

2. A programmer’s most important task before planning the logic of a program is to

a. decide which programming language to use


b. code the problem
c. train the users of the problem
d. understand the problem

3. The two most commonly used tools for planning a program’s logic are _________.

a. ASCII and EBCDIC


b. Java and Visual Basic
c. flowcharts and pseudocode
d. word processors and spreadsheets

4. Which of the following is an example of a syntax error?

a. producing output before accepting input


b. subtracting when you meant to add
c. misspelling a programming language word
d. all of the above

5. Which of the following is an example of a syntax error?

a. performing arithmetic with a value before inputting it


b. accepting two input values when a program requires only one
c. dividing by 3 when you meant to divide by 30
d. all of the above

6. Draw a flowchart or write pseudocode to represent the logic of a program that allows the user
to enter a value. The program multiplies the value by 10 and outputs the result.

7. Draw a flowchart or write pseudocode to represent the logic of a program that allows the user
to enter a value for one edge of a cube. The program calculates the surface area of one side
of the cube, the surface area of the cube, and its volume. The program outputs all the results.

8. Research current rates of monetary exchange. Draw a flowchart or write pseudocode to


represent the logic of a program that allows the user to enter a number of dollars and convert
it to Euros and Japanese yen.

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 21


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Lesson 4 – Introduction to C
What is C?

C is a general-purpose, structured programming language that is powerful, efficient and compact.

Its instructions consists of terms that resemble algebraic expressions, supplemented by certain
English keywords such as if, else, for, and do.

Features modern flow control and data structures, and a rich setof operators.

Contains additional features that allow it to be used at a lower level.

Used for writing system programs and application programs.

History of C

C was developed in the 1970s by Dennis Ritchie at Bell Labs (Murray Hill, New Jersey) in the
process of implementing the Unix operating system on a DEC PDP-11 computer.

Preparing to Program

The Programming Process

- Determine the objective of the program


- Design your solution
o Inputs, outputs and logical steps to achieve the outputs
- Code your solution
- Compile your program
o Handling errors
- Run and Test your program

Structure of a C Program

A program is a sequence of instructions

Instructions of a C program are written as a statement

A statement is terminated by a semicolon (;)

One or more statements forms a block (compound) statement with the individual statements
enclosed within a pair of braces, i.e., { }

All executable statements must be inside a function

A function is where all program activity occurs

Every C program consists of one or more functions

Every C program must contain a special function named main

- The statements within this function is the first one to be executed

Comments are written within the delimiters /*and */

- E.g., /* this is a comment */

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 22


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

First Program : hello.c

Comments in C

The first line /* A simple C program that outputs two lines of text */ starts with /*and ends with */

Anything written between /*and */is called a comment

Comments are not executable statements and they are ignored by the compiler

- They have no effect on the behavior of the resulting program

Comment serves as documentation for the human reader of the program

Preprocessor Directives

The line #include <stdio.h> is called the preprocessor directive

Lines that begin with the #(read hash) sign are preprocessor directives

It is mostly written at the beginning of the program

They are not executable code line but indications for the C preprocessor

The C preprocessor is a tool which filters your source code before it is compiled

In this case, it tells the compiler’s preprocessor that the contents of the file stdio.hshould be
included at the place where #include appears

The file stdio.his called a header file in C and it contains the declaration needed to perform
standard input output operations

The main Function

The next line main() is the first line of a function main

The function main()is required in all C programs

The main function is the starting point of a C program

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 23


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

It is independent from whether it is at the beginning, at the end or by the middle of the code -its
content is always the first to be executed when a program starts

main goes followed by a pair of parenthesis () because it is a function

In C, all functions are followed by a pair of parenthesis () that, optionally, can include arguments
within

The content of the main function follows immediately to its header enclosed between braces {}, as
in our example

The code inside the braces {} are program statements that are to be executed

Main Function Body

The first statement printf("Hello, world\n"); causes the text Hello, world, enclosed in quotes, to be
printed in the standard output device (often known as the console)

Here, printf is a C function that outputs the text

- Anything written within the quotes is printed

The printf function is defined in the file stdio.h

Here \n is a nonprinting character and is one of the escape sequence of C

\n tells to print a new line which causes the next text to be printed on next line

Hence, the next printf causes the text Welcome to ITC213 to be printed on next line

The closing brace } at the last line program signifies the end of the main() function and hence the
end of program

The Build Process

An editor is a specialized word processor used to prepare source modules in the language of
choice (e.g. C, C++, Java, Fortran)

The preprocessor adds in standard pre-written code (boilerplate) from include files you specify
to produce a complete source module

The compiler produces object code for the target computer/ operating system

The linker ties multiple modules together into a complete program

An executable file is a program that will run on the computer. The editor, preprocessor, compiler
and linker are all executables. So is your program

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 24


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Compilation and Linker Errors

A compilation error occurs when the compiler finds something in the source code that it can’t
compile

- A misspelling, typographical error, or any of a dozen other things can be a cause

Linker errors are relatively rare and usually result from misspelling the name of a C library
function

- In this case, you get an Error: undefined symbols: error message, followed by the
misspelled name (preceded by an underscore)

Figure 1 The Build Process

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 25


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Lesson 5 – C Fundamentals
The C Character Set

Set of characters that are used as building blocks to form basic program elements

The C character set consists of

- The 52 upper-and lower-case letters of the Latin alphabet


- The ten decimal digits
- Certain special characters

Identifiers

Names given to various program elements such as variables, functions, labels, and other user
defined items

Naming rule for identifiers:

- Can be a combination of letters, digits and underscore (_), in any order


- The first character of an identifier must not be a digit

In an identifier, upper-and lowercase are treated as different

- For e.g., the identifier countis not equivalent to Countor COUNT

There is no restriction on the length of an identifier

However, only the first 31 characters are generally significant

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 26


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

- For e.g., if your C compiler recognizes only the first 3 characters, the identifiers payand
paymentare same

Keywords

Keywords are reserved words that have standard, predefined meanings in C

You cannot use a keyword for any other purpose other than as a keyword in a C program

- For e.g., you cannot use a keyword for a variable name

The ANSI C defines 32 keywords

Data Types

Data types determine the way a computer organizes data in memory

Determines how much space it occupies in storage and how the bit pattern stored is interpreted

Types can be either predefined or derived

The predefined types in C are the basic types and the type void

Basic types consist of the integer types and the floating types

Basic Data Types

The C language supports four basic data types, each of which are represented differently within
the computer memory

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 27


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Variables

Named location in memory

Used to hold a value that can be modified by a program

Has a type associated with it

Specifying a variable requires two things:

- you must give it a name, and


- you must identify what kind of data you propose

Variable Declaration

When you declare a variable, you instruct the compiler to set aside storage space for the variable

All variables must be declared before you can use them

Constants

Like a variable, a constant is a data storage location used by your program

Unlike a variable, the value stored in a constant can’t be changed during program execution

Every constant has a type that is determined by its value and its notation

C has two types of constants: literal constants and symbolic constants

A literal constant is a value that is typed directly into the source code wherever it is needed

Literal constants are also only referred as constants

Numeric Constants

Floating-point constants:

- written with a decimal point is a floating-point constant

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 28


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

- represented by the C compiler as a double-precision number

Integer Constants

- A constant written without a decimal point

Character Constants

A single character, enclosed in apostrophes

Character constants have integer values that are determined by the computer’s particular
character set

Most computers, and virtually all personal computers, make use of the ASCII character set

In ASCII, each individual character is numerically encoded with its own unique 7-bit combination

Escape Sequences

Certain nonprinting characters, as well as the backslash (\) and the apostrophe ('), can be
expressed in terms of escape sequences

Begins with a backward slash and is followed by one or more special characters

Represents a single character

A character constant written in the form of escape sequence is called backslash character
constant

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 29


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Symbolic Constants

Constant that is represented by a name (symbol) in your program

Like a literal constant, a symbolic constant can’t change

Whenever you need the constant’s value in your program, you use its name as you would use a
variable name

C has two methods for defining a symbolic constant: the #define directive and the const keyword

Initialization of Variables

When a variable, its initial value is undefined

Before using a variable, you should always initialize it to a known value

To initialize a variable, the declaration must consist of a datatype, followed by a variable name,
and equal sign (=) and a literal constant of the appropriate type

Expressions

An expression is any valid combination of different entities for example a constant, a variable, an
array element or a reference to a function

It may also consist of some combination of such entities, interconnected by one or more
operators

Simple Expressions

- The simplest C expression consists of a single item: a simple variable, literal constant or
symbolic constant

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 30


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Complex Expressions

Complex expressions consist of simpler expressions connected by operators

For example:

- -2+8
- is an expression consisting of the sub expressions 2and 8and the addition operator +

You can also write C expressions of great complexity:

Statements

A statement is a complete direction instructing the computer to carry out some task

A statement specifies an action

There are three different classes of statements in C

- Expression statements,
- Compound statements,
- Control statements

Expression Statements

An expression statementconsists of an expression followed by a semicolon

The execution of an expression statement causes the expression to be evaluated

Compound Statements

Consists of several individual statements enclosed within a pairof braces { }

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 31


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

The individual statements may themselves be expression statements, compound statements or


control statements

Provides a capability for embedding statements within other statements

Unlike an expression statement, a compound statement does not end with a semicolon

Control Statements

Used to create special program features, such as logical tests, loops and branches

Many control statements require that other statements be embedded within them

Statements and White Spaces

The term white spacerefers to spaces, tabs, and blank lines in your source code

When the compiler reads a statement in your source code, it looks for the characters in the
statement and for the terminating semicolon, but it ignores white space

An exception: white spaces in string literal constant is not ignored

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 32


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Instructions: Read and understand each given item carefully. Write your final answer clearly and
neatly. No Erasure. Erasure made is considered wrong.

1. What does a declaration provide for a variable?

a. a name
b. a data type
c. both of the above
d. none of the above

2. A variable’s data type describes all of the following except _______.

a. what values the variable can hold


b. the scope of the variable
c. how the variable is stored in memory
d. what operations can be performed with the variable

3. The value stored in an uninitialized variable is ________.

a. null
b. garbage
c. compost
d. its identifier

4. The value 3 is a _________.

a. numeric variable
b. string variable
c. numeric constant
d. string constant

5. The assignment operator __________.

a. is a binary operator
b. has left-to-right associativity
c. is most often represented by a colon
d. two of the above

6. Multiplication has a lower precedence than ______.

a. division
b. subtraction
c. assignment
d. none of the above

7. A hierarchy chart tells you __________.

a. which modules call other modules


b. what tasks are to be performed within each program module
c. when a module executes
d. all of the above

8. What are nonexecuting statements that programmers place within code to explain program
statements in English?

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 33


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

a. pseudocode
b. trivia
c. user documentation
d. comments

9. Program comments are ___________.

a. required to create a runnable program


b. a form of external documentation
c. both of the above
d. none of the above

10. Which of the following is valid advice for naming variables?

a. To save typing, make most variable names one or two letters.


b. To avoid conflict with names that others are using, use unusual or unpronounceable
names.
c. To make names easier to read, separate long names by using underscores or
capitalization for each new word.
d. To maintain your independence, shun the conventions of your organization.

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 34


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Lesson 6 – Operators and Expressions


Operators and Operands

C is very rich in built-in operators

An operator is a symbol that instructs C to perform some operation, or action, on one or more
operands

An operand is something that an operator acts on

Operators that require two operands are binary operators and operators that require one is unary

Operator Categories

Arithmetic Operators

C’s arithmetic operators perform mathematical operations such as addition and subtraction

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 35


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Arithmetic Operators Example

Suppose that aand bare integer variables and cand dare floating-point variables. Also suppose
that c1and c2is a character variable. Their initial values is shown below.

a = 11, b = 3, c = 12.5, d = 2.0, c1 = 'P', c2 = 'T'

Operators Precedence and Associativity

If you use more than one operator in an expression, C uses precedence rule to find out which
operator’s calculation is to be formed.

When two operators have the same precedence, C uses associativityrule to determine which
operation is to be carried out first.

The operators are grouped hierarchically according to their precedence.

Operations with a higher precedence are carried out before operations having a lower
precedence.

The five arithmetic operators are divided into two precedence groups.

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 36


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

- *, / and % have higher precedence than + and –

3 + 4 * 5 is equivalent to 3 + (4 * 5)

Arithmetic operators are evaluated left to right

120 / 4 * 5 is equivalent to (120 / 4) * 5

The natural order of evaluation can be altered through the use of parenthesis

Typecast

The value of an expression can be converted to a different data type if desired

To change the type of an expression, precede the expression with name of type enclosed in
parenthesis

For example, if i is a type int, the expression (float) i casts ito type float. In other words, the
program makes an internal copy of the value of i in floating-point format.

A typecast, or simply cast does not change the data type associated with the expression itself

Multiple Assignment

Multiple assignments of the form identifier 1 = identifier 2 = ... = expression are permissible in C

- x = y = z = 10

The assignments are carried out from right to left

- x = (y = (z = 10));

Assignment operators have lower precedence than other operators and their associativityis right
to left

Compound Assignment

C contains the following five additional assignment operators; +=, -=, /=, *=and %=, often known
as compound assignment

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 37


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Unary Operators

Operators acting upon a single operand are unary operators

Unary Minus(-)

- Used to negate the value of the operand

Increment and Decrement operators (++and --)

- ++ operator causes its operand to be increased by 1


- -- operator causes its operand to be decreased by 1

Prefix and Postfix Increment and Decrement

The increment/decrement operators can be written on either side of its operand

Prefix: the operator is written before its operand (++x)

- Increments/decrements the operand value and the resultant value is used in the
expression

Postfix: the operator is written before its operand (x++)

- The current value of the operand is used in the expression and its value is
incremented/decremented

Other Unary Operators

The sizeof operator

- A compile time operator and, when used with an operand, it returns the number of bytes
the operand occupies
- printf("int takes %d bytes", sizeof(int));

The address of (&) operator

- Returns the memory address of its operand


- int count;
printf("%p", &count);

Typecast: (discussed earlier)

Unary operators have higher precedence than arithmetic operators and their associativityis right-
to-left

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 38


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Relational and Equality Operators

Relational and equality operators are used to compare expressions

Logical Operators

Logical operators let you combine two or more relational expressions into a single expression that
evaluates to either true or false

Suppose i is an integer variable whose value is 7, f is a floating point variable whose value is 5.5,
and c is character constant that represents the character 'w'

The Conditional Operator

The conditional operator is C’s only ternary operator, meaning that it takes three operands

A conditional expression is written in the from

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 39


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

exp1 ? exp2 : exp3

If exp1 evaluates to true (that is, nonzero), the entire expression evaluates to the value of exp2. If
exp1 evaluates to false (that is, zero), the entire expression evaluates as the value of exp3

Operator Precedence Table

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 40


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Instructions: Read and understand each given item carefully. Write your final answer clearly and
neatly. No Erasure. Erasure made is considered wrong.

1. What is the output of this C code?

a. Compile time error


b. -1
c. 1
d. None

2. What is the output of this C code?

a. Compile time error


b. -1 1
c. 1 -1
d. Run time error

3. What is the output of this C code?

a. Run time error


b. 1
c. 3
d. Compile time error

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 41


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Lesson 7 – Data Input and Output


Input/ Output Operators

A program needs to read data in variable names: input operation

Also data stored in variables need to be displayed: output operation

C language does not define any keyword to perform these input/output operations

C language provides functions to perform input/output operations

- getchar, putchar, scanf, printf, getsand puts

All these functions are prototyped under stdio.h

Reading a Single Character through getchar

The getcharfunction reads the next character available from the standard input device (typically a
keyboard) and returns the character read

- Returns EOFwhen it encounters end of file

The character returned can be assigned to a variable for further use

In general terms, a function reference would be written as

variable_name = getchar();

where variable_name refers to some previously defined


character variable

Writing a Single Character through putchar

The putcharfunction can be used to write a single character to a standard output device (typically
a monitor)

It takes the form as shown below:

putchar( character_value ) where character_value can be a character variable or an expression


that evaluates to a character value that is going to be printed

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 42


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Formatted Output Function: printf

Can be used to output data of different types in different formats

Can perform rounding, aligning columns, right/left justification, inserting literal characters,
exponential format, hexadecimal format, and fixed width and precision

The general from of an output function is:

- printf( format-string , arg1 , arg2 , ...., argn )


Here, format-string
is a string and arg1 , arg2 , ..., argn are any valid C expressions

format-string describes the output format

format-string consists of two types of items

- ordinary characters, which are exactly printed as written


- conversion specifications that define the way the subsequent arguments are displayed

Other-arguments ( arg1 , arg2 , ..., argn ): correspond to each conversion specification in format-
string

Example

There must be exactly the same of number of arguments (after the format string) as there are
conversion specifications, and the conversion specifications and the arguments are matched in
order from left to right

The arguments can be any valid expression and they must match the data type as specified in
the conversion specification

Conversion Specifications

Controls the type and format of the value to be printed

Each conversion specification begins with a %and ends with a conversion character.

Conversion character tells the data type of the corresponding argument

Between the %and the conversion character there may be, in order:

- A minus sign, which specifies left adjustment of the converted argument


- A number that specifies the minimum field width
- A period, which separates the field width from the precision
- A number, the precision: exact meaning depends on type printed

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 43


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

- An hif the integer is to be printed as a short, or lif as a long

Conversion Characters

Formatted Input Function: scanf

General-purpose console input routine

Can read all the built-in data types and automatically convert numbers into the proper internal
format

The general form of scanf is

- scanf( format-string , arg1 , arg2 , ..., argn )

scanf reads characters from the standard input, interprets them according to the specification in
format-string , and stores the results in the remaining arguments arg1 , arg2 , ..., argn , each of
which must be a pointer that indicate where the corresponding converted input should be stored

Format String

The format string usually contains conversion specifications, which are used to control conversion
of input. The format string may contain:

- Blanks or tabs, which are not ignored


- Ordinary characters (not %), which are expected to match the next nonwhite space
character of the input stream
- Conversion specifications, consisting of the character %followed by a conversion character
that determines the type of data to be readnext

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 44


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

A conversion specification directs the conversion of the next input field

Any character that cannot be interpreted according to the conversion specification terminates the
current input field, andis put back into the input buffer. This character is then the firstone read for
the next input item

Conversion Character

Skipping Characters

A white-space character in format-string causes scanf to skip one or more white-space characters

A non-white-space character in format-string causes scanfto read and discard matching characters
in the input

Suppressing input

- An * placed before conversion character tells scanfto read a field but not assign to any
variable
- In effect, that input field is skipped. Such a conversion specification corresponds to no
variable argument

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 45


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Lesson 8 – Control Statements


Control Statements and Their Types

A control statement is a statement that causes a group of C statements to execute in a manner


that doesn’t relate to the order it appears in the source code

Types of control statements

- Selection: also known as branching created using if –else, switch


- Repetition: also known as looping created using while, do while, for
- Jump: created using goto, break, continue
- Label: created using case, default, named label

SELECTION

A selection statement is a one in which one group of statement is selected from several available
groups, depending on the outcome of a logical test

C supports two selection statements: if and switch

- In addition, the ? : operator is an alternative to if in certain circumstances

If condition true, print statement executed and program goes on to next statement

- If false, print statement is ignored and the program goes onto the next statement

The if statement

Allows your program to execute a single statement, or a block of statements enclosed between
braces, if a given condition is true

if ( expression )
statement

If expression evaluates to true (any non-zero value), statement is executed. If expression


evaluates to false (0), statement is not executed

- In either case, execution then passes to whatever code follows the ifstatement

expression can be any valid C expression that produces a scalar value and statement can be
simple or compound or even another control statement

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 46


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Flowchart of if

Examples of if

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 47


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

The else clause in an if statements

An if statement can optionally include an else clause

If expression evaluates to true, statement1 is executed. If expression evaluates to false,


statement2 is executed. Both statement1 and statement2 can be compound statements or blocks

Using if-else, you can specify an action to be performed both when the condition is true and
when it is false

Flowchart of if - else

Example of if with else clause

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 48


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Nested-ifs

A nested if is an if that is target of another if or else

In a nested if, an elsestatement always refers to the nearest ifstatement that is within the same
block as the elseand that is not already associated with an else

Example

if-else-if ladder

A common programming construct is the if–else–if ladder because of its appearance

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 49


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

The switch Multiple-Selection Statement

The switch statement

The expression must evaluate to an integer type

The value of expression is tested against the constants present in the case labels

When a match is found, the statement sequence , if present, associated with that case is
executed until the break statement or the end of the switch statement is reached

The statement sequence following defaultlabel is executed if no matches are found

- The default label is optional, and if it is not present, no action takes place if all matches
fail

Examples

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 50


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Things to remember with switch

A switch statement can only be used to test for equality of an expression

- You cannot use relational or logical expression like in if

switch expression must evaluate to an integral value

No two case constants can be same

Omission of a break statement causes execution to go to next case label

The statement sequence after the default label is executed when no caseconstants matches the
expression value

REPETITION

Repetition is the process of executing a group of statements more than one time as long as some
condition remains true

Repetition in C can be implemented using three control statements: while, do –while, for

Psuedocode:

- While there are more items on my shopping list


- Purchase next item and cross it off my list

Also known as iteration/looping statements

Counter-controlled repetition

Definite repetition: know how many times loop will execute

Control variable used to count repetitions

Counter-controlled repetition requires

- The name of a control variable (or loop counter)


- The initial value of the control variable
- A condition that tests for the final value of the control variable (i.e., whether looping
should continue)
- An increment (or decrement) by which the control variable is modified each time through
the loop

Example

A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz are
available to you. Determine the class average on the quiz

Pseudocode:

- Set total to zero

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 51


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

- Set grade counter to one


- While grade counter is less than or equal to ten
Input the next grade
Add the grade into the total
Add one to the grade counter
- Set the class average to the total divided by ten
- Print the class average

The while statement

Executes a block of statements as long as a specified condition is true

while ( expression )

statement

here statement is executed as long as the expression evaluates to true.

- First expression is evaluated


- If expression is nonzero (true), then statement is executed and control is passed back to
he beginning of the while statement, otherwise control passes to next statement following
the whilestatement

Flowchart of while statement

As with if, expression can be any valid C expression that produces a scalar value and statement
can be simple or compound or may be a control statement

The statement inside the while loop must include some feature that eventually alters the value of
the expression , thus providing a stopping condition for the loop

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 52


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

More Examples

Example: Calculation of average grade

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 53


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Sentinel-Controlled Repetition

Problem :

- Develop a class-averaging program that will process an arbitrary number of grades


each time the program is run.
- Unknown number of students
- How will the program know to end?

Use sentinel value

- Also called signal value, dummy value, or flag value


- Indicates “end of data entry.”
- Loop ends when user inputs the sentinel value
- Sentinel value chosen so it cannot be confused with a regular input (such as -1 in this
case)

Example: Calculation of average grade

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 54


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

The for statement

Flowchart of for statement

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 55


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

The for statement

Typically:

- expr1 is used to initialize the loop control variable and is an assignment expression
- expr2 is a logical expression and represents a condition that must be true for the loop to
continue
- expr3 is used to alter the value of control variable and is often an increment/decrement or
assignment expression

for (counter = 1; counter <= 10; counter++)

printf("HelloWorld\n");

Examples

for and while loop

Every forstatement can be written in terms of whilestatement and vice versa

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 56


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

The do-while statement

Similar to the whilestatement but condition for repetition tested after the body of the loop is
performed

do
statement
while (expr);

- First statement is executed, and expr is evaluated


- If the value of expr is nonzero (true), then control passes back to the beginning of the do
statement and process repeats itself
- When expr is zero (false), control passes to next statement following the do-while
statement

Flowchart of do-while statement

As with while, expr can be any valid C


expression that produces a scalar
value and statement can be simple or
compound or may be a control
statement

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 57


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

More Examples

The do-whilestatement is most appropriate when the loop body must be executed at least once

On Loop Statements

Because of the features that are built into the for statement, it is particularly well suited for loops
in which the number of passes is known in advance

while loops should be used when the no of times the statements inside the loop to be executed is
not known in advance

Use do-whileloop, when you want the loop body to execute at least once for the first time
regardless of the outcome of condition

Comma Operator in for statement

Comma operator can be used for multiple initialization and multiple processing of loop control
variables in a forstatement

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 58


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

The 3 expressions in for statement

You can omit, any of the three expression of the for statement

- However, semicolons must be present

If you omit first or third expression, nothing happens at the time of their evaluation

If you omit second expression, it will assume the value 1 (true)

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 59


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

Instructions: Read and understand each given item carefully. Write your final answer clearly and
neatly. No Erasure. Erasure made is considered wrong.

I. Identification

1. A _________ is one that represents only one of two states, usually expressed as true or
false.
2. An if statement contains a tested condition and an action that is taken only when the
expression is _____.
3. An else statement holds the statements that execute only when the tested expression is
_____.
4. _________ operators are the symbols that express comparisons. Examples include ==, >, <,
>=, <=, and <>.
5. A _________ statement is a group of statements inclosed in a curly braces.
6. An ____ logical operator contains two or more decisions; all conditions must be true for an
action to take place.
7. A _______ is a decision within either the if or else of another decision.
8. An ____ logical operator contains two or more decisions; if at least one condition is met, the
resulting action takes place.
9. The logical ____ operator is a symbol that reverses the meaning of a conditional expression.
10. A ____ operator is one that uses only one operand.

II. Multiple Choice

1. If x <= y is true, then _______.


a. x = y is true b. y <= x is true c. x > y is false d. x >= y is false

2. If j != k is true, then _______.


a. j = k is true b. j > k might be true c. j < k might be true d. Both b and c
are true

3. If m is true and n is false, then _______.


a. m AND n is true b. m AND n is false c. m OR n is false d. if m is true,
then n must be true.

4. If p is true and q is false, then _______.


a. p OR q is true b. p OR q is false c. p AND q is true d. p is greater
than q

5. In the following pseudocode, what percentage raise will an employee in Department 8


receive?

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 60


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

a. SMALL_RAISEb. MEDIUM_RAISE c. BIG_RAISE


d. impossible to tell

6. In the following pseudocode, what percentage raise will an employee in Department 10


receive?

a. SMALL_RAISEb. MEDIUM_RAISE c. BIG_RAISE


d. impossible to tell

7. If sales = 100, rate = 0.10, and expenses = 50, which of the following expressions is true?
a. sales >= expenses AND rate < 1 b. sales < 200 OR expenses < 100
c. expenses = rate OR sales = rate d. two of the above

8. If a is true, b is true, and c is false, which of the following expressions is true?


a. a OR b AND c b. a AND b AND c c. a AND b OR c d. two of the
above

9. If d is true, e is false, and f is false, which of the following expressions is true?


a. e OR f AND d b. f AND d OR e c. d OR e AND f d.two of the
above

10. When you use a range check, you compare a variable to the _________ value in the
range.
a. lowest b. middle c. highest d. lowest or
highest

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 61


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

I. Multiple choices (RX2)

1. The structure that allows you to write one set of instructions that operates on multiple,
separate sets of data is the __________.
A. Sequence B. Loop C. Selection D. Case
2. The loop that frequently appears in a program’s mainline logic __________.
A. Always depends on whether a variable equals 0.
B. Is an example of an infinite loop.
C. Is an unstructured loop.
D. Works correctly based on the same logic as other loops.
3. Which of the following is not a step that must occur with every correctly working loop?
A. Initialize a loop control variable before the loop starts.
B. Compare the loop control value to a sentinel during each iteration.
C. Set the loop control value equal to a sentinel during each iteration.
D. Alter the loop control variable during each iteration.
4. The statements executed within a loop are known collectively as the __________.
A. Loop body B. Loop controls C. Sequences D. Sentinels
5. A counter keeps track of _________.
A. The number of times an event has occurred.
B. The number of machine cycles required by a segment of a program.
C. The number of loop structures within a program.
D. The number of times software has been revised.
6. Adding 1 to a variable is also called _________ it.
A. Digesting B. Resetting C. Decrementing D. Incrementing
7. Which of the following is a definite loop?
A. A loop that executes as long as a user continues to enter valid data.
B. A loop that executes 1000 times
C. Both of the above
D. None of the above
8. Which of the following is an indefinite loop?
A. A loop that executes exactly 10 times.
B. A loop that follows a prompt that asks a user how many repetitions to make and uses
the value to control the loop.
C. Both of the above
D. None of the above
9. When you decrement a variable, you __________.
A. Set it to 0 B. Reduce it by one-tenth C. Subtract a value from it D.
Remove it from a program

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 62


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

10. When two loops are nested, the loop that is contained by the other is the __________
loop.
A. Captive B. Unstructured C. Inner D. Outer
11. When loops are nested, __________.
A. They typically share a loop control variable.
B. One must end before other begins.
C. Both must be the same type-definite or indefinite.
D. None of the above
12. Most programmers use a for loop __________.
A. For every loop they write.
B. When they know the exact number of times a loop will repeat.
C. When a loop must repeat many times.
D. When a loop will not repeat.
13. A report that lists only totals, with no details about individual records, is a(n)
__________ report.
A. Accumulator B. Final C. Group D. Summary
14. Typically, the value added to a counter variable is ___________.
A. 0 B. 1 C. The same for each iteration D. Different in each
iteration
15. Typically, the value added to an accumulator variable is __________.
A. 0 B. 1 C. The same for each iteration D. Different in each
iteration
16. After an accumulator or counter variable is displayed at the end of a program, it is best
to __________.
A. Delete the variable from the program.
B. Reset the variable to 0.
C. Subtract 1 from the variable.
D. None of the above.
17. When you __________, you make sure data items are the correct type and fall within
the correct range.
A. Validate data B. Employ offensive programming C. Use object
orientation
D. Count loop iterations.
18. Overriding a user’s entered value by setting it to a predetermined value is known as
__________.
A. Forcing B. Accumulating C. Validating D. Pushing
19. To ensure that a user’s entry is the correct data type, frequently you __________.
A. Prompt the user to verify that the type is correct.
B. Use a method built into the programming language.
C. include a statement at the beginning of the program that lists the data types allowed.
D. All of the above
20. A variable might hold an incorrect value even when it is __________.
A. The correct data type
B. Within a required range
C. A constant coded by the programmer
D. All of the above

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 63


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

II. Output Tracing (5 PTS)


What is the output by each of the program below.
A. B.

C. D.

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 64


University of Cebu
Expanded Tertiary Education Equivalency Accreditation Program
Bachelor of Science in Computer Engineering

References

1. Computer Science: A structured Programming Approach Using C 3rd Edition by


Behrouz A. Forouzan
2. Problem Solving and Program Design in C 2nd Edition by Hanly Koffman
3. Programming Logic & Design, Comprehensive 9th Edition by Joyce Farrell

CpE 211 – Computer Fundamentals by Engr. Bryan A. Camello 65

You might also like