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

COMP

The document provides an overview of computers and their fundamentals, including their functions, advantages, and applications. It discusses how computers accept data as input, store and process it, generate output, and control these functions. It outlines computers' advantages like speed, accuracy, storage capacity, diligence, versatility, reliability, and automation. It also notes computers' disadvantages like lack of intelligence, dependency on humans, environmental requirements, and inability to feel. The document then discusses various applications of computers in fields such as business, banking, insurance, education, marketing, healthcare, engineering design, the military, communication, and government.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
233 views

COMP

The document provides an overview of computers and their fundamentals, including their functions, advantages, and applications. It discusses how computers accept data as input, store and process it, generate output, and control these functions. It outlines computers' advantages like speed, accuracy, storage capacity, diligence, versatility, reliability, and automation. It also notes computers' disadvantages like lack of intelligence, dependency on humans, environmental requirements, and inability to feel. The document then discusses various applications of computers in fields such as business, banking, insurance, education, marketing, healthcare, engineering design, the military, communication, and government.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 367

1.

Computer Fundamentals ─ Overview

Today’s world is an information-rich world and it has become a necessity for everyone to know
about computers. A computer is an electronic data processing device, which accepts and
stores data input, processes the data input, and generates the output in a required format.

The purpose of this tutorial is to introduce you to Computers and its fundamentals.

Functionalities of a Computer
If we look at it in a very broad sense, any digital computer carries out the following five
functions:

Step 1 - Takes data as input.

Step 2 - Stores the data/instructions in its memory and uses them as required.

Step 3 - Processes the data and converts it into useful information.

Step 4 - Generates the output.

Step 5 - Controls all the above four steps.

Advantages of Computers
Following are certain advantages of computers.

High Speed
 Computer is a very fast device.

 It is capable of performing calculation of very large amount of data.

 The computer has units of speed in microsecond, nanosecond, and even the
picosecond.

5
 It can perform millions of calculations in a few seconds as compared to man who will
spend many months to perform the same task.

Accuracy
 In addition to being very fast, computers are very accurate.

 The calculations are 100% error free.

 Computers perform all jobs with 100% accuracy provided that the input is correct.

Storage Capability
 Memory is a very important characteristic of computers.

 A computer has much more storage capacity than human beings.

 It can store large amount of data.

 It can store any type of data such as images, videos, text, audio, etc.

Diligence
 Unlike human beings, a computer is free from monotony, tiredness, and lack of
concentration.

 It can work continuously without any error and boredom.

 It can perform repeated tasks with the same speed and accuracy.

Versatility
 A computer is a very versatile machine.

 A computer is very flexible in performing the jobs to be done.

 This machine can be used to solve the problems related to various fields.

 At one instance, it may be solving a complex scientific problem and the very next
moment it may be playing a card game.

Reliability
 A computer is a reliable machine.
 Modern electronic components have long lives.

6
 Computers are designed to make maintenance easy.

Automation
 Computer is an automatic machine.

 Automation is the ability to perform a given task automatically. Once the computer
receives a program i.e., the program is stored in the computer memory, then the
program and instruction can control the program execution without human interaction.

Reduction in Paper Work and Cost


 The use of computers for data processing in an organization leads to reduction in paper
work and results in speeding up the process.

 As data in electronic files can be retrieved as and when required, the problem of
maintenance of large number of paper files gets reduced.

 Though the initial investment for installing a computer is high, it substantially reduces
the cost of each of its transaction.

Disadvantages of Computers
Following are certain disadvantages of computers.

No I.Q.
 A computer is a machine that has no intelligence to perform any task.
 Each instruction has to be given to the computer.
 A computer cannot take any decision on its own.

Dependency
 It functions as per the user’s instruction, thus it is fully dependent on humans.

Environment
 The operating environment of the computer should be dust free and suitable.

No Feeling
 Computers have no feelings or emotions.

 It cannot make judgment based on feeling, taste, experience, and knowledge unlike
humans.

7
2. Computer Fundamentals ─ Applications

In this chapter, we will discuss the application of computers in various fields.

Business
A computer has high speed of calculation,
diligence, accuracy, reliability, or versatility which
has made it an integrated part in all business
organizations.

Computer is used in business organizations for:

 Payroll calculations
 Budgeting
 Sales analysis
 Financial forecasting
 Managing employee database
 Maintenance of stocks, etc.

Banking
Today, banking is almost totally dependent on
computers.

Banks provide the following facilities:

 Online accounting facility, which includes


checking current balance, making
deposits and overdrafts, checking interest
charges, shares, and trustee records.

 ATM machines which are completely


automated are making it even easier for
customers to deal with banks.

8
Insurance
Insurance companies are keeping all records up-
to-date with the help of computers. Insurance
companies, finance houses, and stock broking
firms are widely using computers for their
concerns.

Insurance companies are maintaining a database


of all clients with information showing:

 Procedure to continue with policies


 Starting date of the policies
 Next due installment of a policy
 Maturity date
 Interests due
 Survival benefits
 Bonus

Education
The computer helps in providing a lot of facilities in the education system.

 The computer provides a tool in the education system known as CBE (Computer Based
Education).

 CBE involves control, delivery, and


evaluation of learning.

 Computer education is rapidly increasing


the graph of number of computer students.

 There are a number of methods in which


educational institutions can use a computer
to educate the students.

 It is used to prepare a database about


performance of a student and analysis is carried out on this basis.

Marketing

9
In marketing, uses of the computer are following:

 Advertising - With computers, advertising


professionals create art and graphics, write
and revise copy, and print and disseminate
ads with the goal of selling more products.

 Home Shopping - Home shopping has


been made possible through the use of
computerized catalogues that provide
access to product information and permit
direct entry of orders to be filled by the
customers.

Healthcare
Computers have become an important part in hospitals, labs, and dispensaries. They are
being used in hospitals to keep the record of patients and medicines. It is also used in scanning
and diagnosing different diseases. ECG, EEG, ultrasounds and CT scans, etc. are also done by
computerized machines.

Following are some major fields of health care in which computers are used.

 Diagnostic System - Computers are used to collect data and identify the cause of
illness.

 Lab-diagnostic System - All tests can be


done and the reports are prepared by
computer.

 Patient Monitoring System - These are


used to check the patient's signs for
abnormality such as in Cardiac Arrest, ECG,
etc.

 Pharma Information System


- Computer is used to check drug labels,
expiry dates, harmful side effects, etc.

 Surgery - Nowadays, computers are also used in performing surgery.

Engineering Design
Computers are widely used for Engineering purpose.

One of the major areas is CAD (Computer Aided Design) that provides creation and
modification of images. Some of the fields are:

10
 Structural Engineering - Requires stress
and strain analysis for design of ships,
buildings, budgets, airplanes, etc.

 Industrial Engineering - Computers


deal with design, implementation, and
improvement of integrated systems of
people, materials, and equipment.

 Architectural Engineering - Computers


help in planning towns, designing
buildings, determining a range of buildings
on a site using both 2D and 3D drawings.

Military
Computers are largely used in defence. Modern
tanks, missiles, weapons, etc. Military also
employs computerized control systems. Some
military areas where a computer has been used
are:

 Missile Control
 Military Communication
 Military Operation and Planning
 Smart Weapons

Communication
Communication is a way to convey a message, an idea, a picture, or speech that is received
and understood clearly and correctly by the person
for whom it is meant. Some main areas in this
category are:

 E-mail
 Chatting
 Usenet
 FTP
 Telnet
 Video-conferencing

11
Government
Computers play an important role in government services. Some major fields in this category
are:

 Budgets
 Sales tax department
 Income tax department
 Computation of male/female ratio
 Computerization of voters lists
 Computerization of PAN card
 Weather forecasting

12
3. Computer Fundamentals ─ Generations

Generation in computer terminology is a change in technology a computer is/was being used.


Initially, the generation term was used to distinguish between varying hardware technologies.
Nowadays, generation includes both hardware and software, which together make up an
entire computer system.

There are five computer generations known till date. Each generation has been discussed in
detail along with their time period and characteristics. In the following table, approximate
dates against each generation has been mentioned, which are normally accepted.

Following are the main five generations of computers.

Sr.
Generation & Description
No.

First Generation
1
The period of first generation: 1946-1959. Vacuum tube based.

Second Generation
2 The period of second generation: 1959-1965. Transistor based.

Third Generation
3 The period of third generation: 1965-1971. Integrated Circuit based.

Fourth Generation
4 The period of fourth generation: 1971-1980. VLSI microprocessor based.

Fifth Generation
5 The period of fifth generation: 1980-onwards. ULSI microprocessor based.

First Generation Computers


The period of first generation was from 1946-1959. The computers of first generation used
vacuum tubes as the basic components for memory and circuitry for CPU (Central Processing
Unit). These tubes, like electric bulbs, produced a lot of heat and the installations used to fuse
frequently. Therefore, they were very expensive and only large organizations were able to
afford it.
13
In this generation, mainly batch processing operating system was used. Punch cards, paper
tape, and magnetic tape was used as input and output devices. The computers in this
generation used machine code as the programming language.

The main features of the first generation are:

 Vacuum tube technology


 Unreliable
 Supported machine language only
 Very costly
 Generated a lot of heat
 Slow input and output devices
 Huge size
 Need of AC

14
 Non-portable
 Consumed a lot of electricity

Some computers of this generation were:

 ENIAC
 EDVAC
 UNIVAC
 IBM-701
 IBM-650

Second Generation Computers


The period of second generation was from 1959-1965. In this generation, transistors were
used that were cheaper, consumed less power, more compact in size, more reliable and faster
than the first generation machines made of vacuum tubes. In this generation, magnetic cores
were used as the primary memory and magnetic tape and magnetic disks as secondary
storage devices.

In this generation, assembly language and high-level programming languages like FORTRAN,
COBOL were used. The computers used batch processing and multiprogramming operating
system.

15
The main features of second generation are:

 Use of transistors
 Reliable in comparison to first generation computers
 Smaller size as compared to first generation computers
 Generated less heat as compared to first generation computers
 Consumed less electricity as compared to first generation computers
 Faster than first generation computers
 Still very costly
 AC required
 Supported machine and assembly languages

Some computers of this generation were:

 IBM 1620
 IBM 7094
 CDC 1604
 CDC 3600
 UNIVAC 1108

Third Generation Computers


The period of third generation was from 1965-1971. The computers of third generation used
Integrated Circuits (ICs) in place of transistors. A single IC has many transistors, resistors,
and capacitors along with the associated circuitry.

The IC was invented by Jack Kilby. This development made computers smaller in size, reliable,
and efficient. In this generation remote processing, time-sharing, multi-programming
operating system were used. High-level languages (FORTRAN-II TO IV, COBOL, PASCAL PL/1,
BASIC, ALGOL-68 etc.) were used during this generation.

16
The main features of third generation are:

 IC used
 More reliable in comparison to previous two generations
 Smaller size
 Generated less heat
 Faster
 Lesser maintenance
 Costly
 AC required
 Consumed lesser electricity
 Supported high-level language

Some computers of this generation were:

 IBM-360 series
 Honeywell-6000 series
 PDP (Personal Data Processor)
 IBM-370/168
 TDC-316

Fourth Generation Computers


The period of fourth generation was from 1971-1980. Computers of fourth generation used
Very Large Scale Integrated (VLSI) circuits. VLSI circuits having about 5000 transistors and
17
other circuit elements with their associated circuits on a single chip made it possible to have
microcomputers of fourth generation.

Fourth generation computers became more powerful, compact, reliable, and affordable. As a
result, it gave rise to Personal Computer (PC) revolution. In this generation, time sharing,
real time networks, distributed operating system were used. All the high-level languages like
C, C++, DBASE etc., were used in this generation.

The main features of fourth generation are:

 VLSI technology used


 Very cheap
 Portable and reliable
 Use of PCs
 Very small size
 Pipeline processing
 No AC required
 Concept of internet was introduced
 Great developments in the fields of networks
 Computers became easily available

Some computers of this generation were:

 DEC 10

18
 STAR 1000
 PDP 11
 CRAY-1(Super Computer)
 CRAY-X-MP(Super Computer)

Fifth Generation Computers


The period of fifth generation is 1980-till date. In the fifth generation, VLSI technology became
ULSI (Ultra Large Scale Integration) technology, resulting in the production of microprocessor
chips having ten million electronic components.

This generation is based on parallel processing hardware and AI (Artificial Intelligence)


software. AI is an emerging branch in computer science, which interprets the means and
method of making computers think like human beings. All the high-level languages like C and
C++, Java, .Net etc., are used in this generation.

AI includes:

 Robotics
 Neural Networks
 Game Playing
 Development of expert systems to make decisions in real-life situations
 Natural language understanding and generation

The main features of fifth generation are:


19
 ULSI technology
 Development of true artificial intelligence
 Development of Natural language processing
 Advancement in Parallel Processing
 Advancement in Superconductor technology
 More user-friendly interfaces with multimedia features
 Availability of very powerful and compact computers at cheaper rates

Some computer types of this generation are:

 Desktop
 Laptop
 NoteBook
 UltraBook
 ChromeBook

20
4. Computer Fundamentals ─ Types

Computers can be broadly classified by their speed and computing power.

Sr.
Type Specifications
No.

PC (Personal It is a single user computer system having moderately


1
Computer) powerful microprocessor

It is also a single user computer system, similar to personal


2 Workstation
computer however has a more powerful microprocessor

It is a multi-user computer system, capable of supporting


3 Mini Computer
hundreds of users simultaneously.

It is a multi-user computer system, capable of supporting


4 Main Frame hundreds of users simultaneously. Software technology is
different from minicomputer.

It is an extremely fast computer, which can execute


5 Supercomputer
hundreds of millions of instructions per second.

PC (Personal Computer)
A PC can be defined as a small, relatively inexpensive computer designed for an individual
user. PCs are based on the microprocessor technology that enables manufacturers to put an
entire CPU on one chip. Businesses use personal
computers for word processing, accounting,
desktop publishing, and for running spreadsheet
and database management applications. At home,
the most popular use for personal computers is
playing games and surfing the Internet.

Although personal computers are designed as


single-user systems, these systems are normally
linked together to form a network. In terms of
power, now-a-days high-end models of the
Macintosh and PC offer the same computing power
and graphics capability as low-end workstations by
Sun Microsystems, Hewlett-Packard, and Dell.

21
Workstation
Workstation is a computer used for engineering applications (CAD/CAM), desktop publishing,
software development, and other such types of applications which require a moderate amount
of computing power and relatively high quality graphics capabilities.

Workstations generally come with a large, high-resolution graphics screen, large amount of
RAM, inbuilt network support, and a graphical user
interface. Most workstations also have mass
storage device such as a disk drive, but a special
type of workstation, called diskless workstation,
comes without a disk drive.

Common operating systems for workstations are


UNIX and Windows NT. Like PC, workstations are
also single-user computers like PC but are typically
linked together to form a local-area network,
although they can also be used as stand-alone
systems.

Minicomputer
It is a midsize multi-processing system capable of supporting up to 250 users simultaneously.

Mainframe
Mainframe is very large in size and is an expensive computer capable of supporting hundreds
or even thousands of users simultaneously. Mainframe executes many programs concurrently
and supports many simultaneous execution of programs.

22
Supercomputer
Supercomputers are one of the fastest computers currently available. Supercomputers are
very expensive and are employed for specialized applications that require immense amount
of mathematical calculations (number crunching).

For example, weather forecasting, scientific simulations, (animated) graphics, fluid dynamic
calculations, nuclear energy research, electronic design, and analysis of geological data (e.g.
in petrochemical prospecting).

23
5. Computer Fundamentals ─ Components

All types of computers follow the same basic logical structure and perform the following five
basic operations for converting raw input data into information useful to their users.

Sr. No. Operation Description

The process of entering data and instructions into the


1 Take Input
computer system.

Saving data and instructions so that they are available for


2 Store Data
processing as and when required.

Performing arithmetic, and logical operations on data in


3 Processing Data
order to convert them into useful information.

Output The process of producing useful information or results for


4
Information the user, such as a printed report or visual display.

Control the Directs the manner and sequence in which all of the above
5
workflow operations are performed.

Input Unit
24
This unit contains devices with the help of which we enter data into the computer. This unit
creates a link between the user and the computer. The input devices translate the information
into a form understandable by the computer.

CPU (Central Processing Unit)


CPU is considered as the brain of the computer. CPU performs all types of data processing
operations. It stores data, intermediate results, and instructions (program). It controls the
operation of all parts of the computer.

CPU itself has the following three components:

 ALU (Arithmetic Logic Unit)


 Memory Unit
 Control Unit

Output Unit
The output unit consists of devices with the help of which we get the information from the
computer. This unit is a link between the computer and the users. Output devices translate
the computer's output into a form understandable by the users.

25
End of ebook preview
If you liked what you saw…
Buy it from our store @ https://store.tutorialspoint.com

26
Computer Programming 1

Prepared by:

Roel Lauron
Instructional Resources/ Textbook

References:
005.133/B789/2013 Bronson, Gary J. C++ Programming: Principles and Practices for Scientists and Engineers. Cengage
Learning, 2013.

005.133/F769/2011 Forouzan, Behrouz A. Foundations of C Programming. Cengage Learning, 2011.

005.133/M295/2011 Malik, D.S. C++ Programming: Problem Analysis to Program Design. Cengage Learning, 2011.

005.133/Sch644/2011 Scholl, T., Nugent, G. C++ Programming Problem Analysis to Program Design (Lab Manual). Cengage
Learning, 2011

005.133/V74/2008 Vine, Micheal A. C Programming for the Absolute Beginner, 2008


Internet Sources:

www.course.com
www.thomsonlearning.com
www.tutorialspoint.com/cprogramming/
www.cprogramming.com/tutorial/c-tutorial.html
www.iu.hio.no/~mark/CTutorial/CTutorial.html
http://fresh2refresh.com/c-tutorial-for-beginners
What is computer Programming?
Computer programming is creating a sequence of
instructions to enable the computer to do
something.

Computer programming is not just programming


language syntax and using development
environment. At its core, computer
programming is solving problems.
What is a programming language?

A programming language is an artificial


language that can be used to control the
behavior of a machine, particularly a
computer.
Programming Language Translation
 Source Program -- program written in a high-
level programming language.
 Object Program -- the source program after it
has been translated into machine language.
 Translator Program -- the program that
translates the source program into the object
program. Can be either a compiler or an
interpreter.
Compilers vs. Interpreters
 Compiler -- spends some time evaluating the entire program and
then translates all the programming statements of a program into a
machine language program, which is then executed at once.
 Interpreter -- translates interactively each programming statement
into an immediately usable machine language instruction. Although
an interpreter slows down the execution speed of a program
somewhat, it does not require extra steps to compile and link like a
compiler.
 In a production environment where throughput is more critical, a
compiled language is preferred.
 Any high-level language can either be interpreted or compiled.
Categories of Programming
 Systems programming involves writing programs that enable
a computer to carry out its basic internal functions as well as
some other specialized functions. Examples of systems
programs include operating systems, device drivers, and utility
programs.
 Applications programming refers to the process of
developing programs to be used for specific applications, such
as a business application (e.g., computing benefits to be paid to
different employee classifications) or an academic application
(e.g., determining who qualifies for which scholarship, based on
specified eligibility criteria).
Stages in the Applications Programming Process
1.Problem statement: The programming process begins
with a clear, written statement of the problem to be solved
by the computer.
2.Algorithm development: Once the problem has been
clearly stated and all the requirements have been
understood, the next step is to develop the program logic
necessary for accomplishing the task.
*An algorithm is defined as a logical sequence of steps
that must be performed in order to accomplish a given
task.
•Sample Tool: Flowchart
Stages in the Applications Programming Process
3. Program coding: When the programmer is satisfied with the
efficacy of the logic developed in the preceding step, it is time
to convert that logic (in either flowchart or pseudocode form)
to the specific syntax of the programming language that will
be used.
4. Program testing: The coded program is next checked for
errors.
5. Program documentation: The programming process is
complete when the program has been fully documented.
Computer Programming 1
Five steps to define a programming problem:
1. Restate the problem.
2. Analyze the problem.
3. Identify the output.
4. Identify the input.
5. Identify the process.
Common Programming Errors

1. Syntax Errors
- occurs when your code violates one or more
grammar rules of C and is detected by the compiler
as it attempts to translate your program.
Note: If a statement has a syntax error, it cannot be
translated and your program will not be executed.
Common Programming Errors
2. Run-time Errors
- are detected errors and displayed by the compiler during the
execution of the program.
- occurs when the program directs the computer to perform
illegal operation, such as dividing a number by zero.
- an attempt to perform an invalid operation, detected during
program execution.
Note: When a run-time error occurs, the computer will stop
executing your program and will display a diagnostic message
that indicates the line where the error was detected.
Common Programming Errors

3. Logic Errors
- occur when a program follows a faulty algorithm.
- do not cause a run-time error and do not display
error messages, so are very difficult to detect.

Note: The only sign of a logic error may be incorrect


program output.
C History
Dennis Ritchie – developed C at AT&T
Bell Laboratories.

C was first developed for system


programming.
C Programming Language
C Language
one of the most popular languages of modern
times.
Programs written in C are portable across
different environments
Applications created using the C language
range from operating systems to database
systems.
C Programming Language

 C is a programming language designed by


Dennis Ritchie in 1972 at AT&T Bell
Laboratories.
 C was designed as a language for systems
programming, as a way to fully access the
computer’s power without becoming caught up
in the tedious writing of assembly language.
General Description of C

C is a concise language
 it has only about 32
keywords
 it encourages concise code.
General Description of C

C is flexible, powerful, and


well suited for programming
several levels of abstraction.
General Description of C
 C is a modular language
 The function is the primary program
structure, but functions may not be
nested.
 The C programmer depends on a library
of function, many of which becomes part
of the standard language definition.
General Description of C
 C is the basis for C++.
 C++ programmer also uses many of the
constructs and methodologies that are
routinely used by the C programmer.
 learning C can be considered a first step
in learning C++.
General Description of C

C is weakly typed
 allowing quite a bit of data
conversion and providing
minimal run time checking.
C Language Elements

The C Preprocessor - a program that is


executed before the source code is compiled.
DIRECTIVES – how C preprocessor commands are
called, and begin with a pound / hash symbol (#).
No white space should appear before the #, and a
semi colon is NOT required at the end.
C Language Elements
Two Common Directives:
1. #include – gives program access to a library.

- causes the preprocessor to insert definitions


from a standard header file into the program
before compilation.
- tells the preprocessor that some names used in
the program are found in the standard header
file.
C Language Elements
Two Common Directives:
2. #define – allows you to make text
substitutions before compiling the
program.
- by convention, all identifiers that are to
be changed by the preprocessor are
written in capital letters.
C Language Elements
#include <stdio.h>
#define MIN 0 /* #defines */
#define MAX 10
#define TRUE 1
#define FALSE 0
int main() { /* beginning of program */
int a;
int okay=FALSE;/*the compiler sees this as int okay=0;*/
while(!okay) {
printf("Input an integer between %d and %d: ", MIN, MAX); scanf("%d",
&a);
if(a>MAX) {
printf("\nToo large.\n"); }
else if(a<MIN) {
printf("\nToo small.\n"); }
else { printf("\nThanks.\n");
okay = TRUE; }
} return 0; }
C Language Elements
Libraries – C implementations that
contain collections of useful
functions and symbols that may be
accessed by a program.

Note: A C system may expand the number of


operation available by supplying additional
libraries. Each library has a standard
header file whose name ends with the
symbol .h.
C Language Elements
Commenting Your Code
You can add comments to your code by enclosing your
remarks within /* and */. However, nested comments
aren't allowed.
A few properties of comments:
• They can be used to inform the person viewing the code
what the code does. This is helpful when you revisit the
code at a later date.
• The compiler ignores all the comments. Hence, commenting
does not affect the efficiency of the program.
• You can use /* and */ to comment out sections of code
when it comes to finding errors, instead of deletion.
C Language Elements
Here are examples of commented code:

/* Comments spanning several */


/* lines can be commented*/
/* out like this!*/
/* But this is a simpler way of doing it! */
// These are C++
// style comments
// and should NOT
// be used with C!!
/* /* NESTED COMMENTS ARE ILLEGAL!! */ */
C Language Elements
Function Main
Every C program has a main function. This
is where program execution begins.
Body- the remaining line of the program in
the body.
Braces {} – enclose the body of the
function.
- indicates the beginning and end of the
function main.
C Language Elements
Two parts of the function body:
1. Declarations – the part of the program that
tells the compiler the names of memory
cells in a program needed in the function,
commonly data requirements identified
during problem analysis.
2. Executable statements – derived statements
from the algorithm into machine language
and later executed.
C Language Elements
Your First Program

#include <stdio.h>
#include <conio.h>

main()
{
printf("Hello World!\n"); //syntax of printf
getch();
}
C Language Elements
Reserved Words
In C, a reserved word is defined as
the word that has special meaning
in C and cannot be used for other
purposes.

Examples: int, void, double, return,


printf, scanf, if, while, do, for
C Language Elements
Punctuation Marks
/* */, // -(slash asterisk) used to enclose a single line remarks.
“ -(double quotation) used to display series of characters,
and initializing string constant.
; -(semicolon) statement separator
, -(comma) used to separate one variable to another
= -(equal sign) used as assignment operator
‘ -(single quotation) used for initializing character
expression
& -(ampersand) used as address operator
{} -(open/close braces) denotes the beginning and end of
the program.
2-3 Identifiers
One feature present in all computer languages is the
identifier. Identifiers allow us to name data and other
objects in the program. Each identified object in the
computer is stored at a unique address. If we didn’t have
identifiers that we could use to symbolically represent data
locations, we would have to know and use object’s
addresses. Instead, we simply give data identifiers and let
the compiler keep track of where they are physically
located.
C Language Elements
Reserved Words
In C, a reserved word is defined as
the word that has special meaning
in C and cannot be used for other
purposes.

Examples: int, void, double, return


Variables, Data Types and Constants
Naming Conventions (Identifiers)

1. Names are made up of letters and digits.


2. The first character must be a letter.
3. C is case-sensitive, example ‘s’ is not the same with ‘S’.
4. The underscore symbol (_) is considered as a letter in C.
It is not recommended to be used, however, as the first
character in a name.
5. At least the first 3 characters of a name are significant.
Variables, Data Types and Constants
Names... Example

CANNOT start with a number 2i


CAN contain a number elsewhere h2o
CANNOT contain any arithmetic operators... r*s+t
CANNOT contain any other punctuation marks... #@x%£!!a
CAN contain or begin with an underscore _height_
CANNOT be a C keyword struct
CANNOT contain a space im stupid
CAN be of mixed cases Squared
Note
An identifier must start with a letter or underscore:
it may not have a space or a hyphen.
Note
C is a case-sensitive language.
Variables, Data Types and Constants
Variables - are like containers in your
computer's memory - you can store values
in them and retrieve or modify them when
necessary.
- associated with a memory cell whose
value can change as the program executes.

Variable declaration – statements that


communicate to the C compiler the names
of all variables used in the program and the
kind of information stored in each variable.
- also tells how that information will be
represented in memory.
Variables, Data Types and Constants
Syntax for Declarations:

data type variable_list;

Ex. int x,age;


float sum,a,b;
char middle_intial;
Note
When a variable is defined, it is not initialized.
We must initialize any variable requiring
prescribed data when the function starts.
Variables, Data Types and Constants
Data Type – a set of values and a set
of operations that can be performed
on those values.

Standard Predefined Data Type in C:


 char

 double/float

 int
Variables, Data Types and Constants
Seven Basic C Data Types:
1. Text (data type char) – made up of single characters (example x,#,9,E)
and strings (“Hello”), usually 8 bits, or 1 byte with the range of 0 to 255.
2. Integer values – those numbers you learned to count with.
3. Floating-point values – numbers that have fractional portions such as
12.345, and exponents 1.2e+22.
4. Double-floating point values – have extended range of 1.7e-308 to
1.7e+308.
5. Enumerated data types – allow for user-defined data types.
6. void – signifies values that occupy 0 bit and have no value. You can also
use this type to create generic pointers.
7. Pointer – does not hold information as do the other data types. Instead,
each pointer contains the address of the memory location.
Variables, Data Types and Constants
int - data type
int is used to define integer numbers.
Ex.
{ int Count;
Count = 5; }

float - data type


float is used to define floating point numbers.
Ex.
{ float Miles;
Miles = 5.6; }
FIGURE 2-10 Floating-point Types
Variables, Data Types and Constants
double - data type
double is used to define BIG floating point numbers. It reserves twice
the storage for the number. On PCs this is likely to be 8 bytes.
Ex.
{ double Atoms;
Atoms = 2500000; }

char - data type


char defines characters.
Ex.
{ char Letter;
Letter = 'x'; }
Variables, Data Types and Constants
Modifiers

The three data types above have the following


modifiers.
 short
 long
 signed
 unsigned
The modifiers define the amount of storage allocated
to the variable. The amount of storage allocated is
not cast in stone. ANSI has the following rules:
short int <= int <= long int
float <= double <= long double
Variables, Data Types and Constants
Type Bytes Bits Range
short int 2 16 -32,768 -> +32,767 (32kb)
unsigned short int 2 16 0 -> +65,535 (64Kb)
unsigned int 4 32 0 -> +4,294,967,295 ( 4Gb)
int 4 32 -2,147,483,648 -> +2,147,483,647 (2Gb)
long int 4 32 -2,147,483,648 -> +2,147,483,647 (2Gb)
signed char 1 8 -128 -> +127
unsigned char 1 8 0 -> +255
float 4 32
double 8 64
long double 12 96
Variables, Data Types and Constants
Constants – identifiers that are having a
constant value all throughout the program
execution.
- also fixed values that may not be altered
by the program.

Examples:
1. Character constants – enclosed between
single quotes. Ex. ‘A’, ‘+’
2. Integer constants – specified as numbers
without fractional components.
Ex. 5 and -160
Variables, Data Types and Constants
 Floating constants – require the use of
decimal point followed by the number’s
fractional components. Ex. 16.234
 String constants – set of characters
enclosed by double quotes. Ex. “bag”
and “this is good”
 Backslash character constants –
enclosing all character constants in
single quotes that works for most
printing characters. Ex. g = ‘\t’
Variables, Data Types and Constants
SEQUENCE NAME MEANING
\a Alert Sound a beep
\b Backspace Backs up one character
\f Form feed Starts a new screen of page
\n New line Moves to the beginning of the next line

\r Carriage Return Moves to the beginning of the current line


\t Horizontal tab Moves to the next Tab position
\v Vertical tab Moves down a fixed amount
\\ Backslash Displays an actual backslash
\’ Single quote Displays an actual single quote
\? Question mark Displays an actual question mark
\”” Double quote Displays an actual double quote
Variables, Data Types and Constants
Defining Constants

 #define preprocessor
- allows us to define symbolic names and
constants.
A quick example:
#define PI 3.14159
This statement will translate every occurrence of PI in
the program to 3.14159.
Here is a more complete example:
#define PI 3.14159 main() { int r=10; float cir; cir =
PI * (r*r); }
Variables, Data Types and Constants
Defining Constants

 The const keyword.


- used to create a read only variable. Once initialized, the value of the variable
cannot be changed but can be used just like any other variable.
const syntax:
main()
{ const float pi = 3.14; }
The const keyword is used as a qualifier to the following data types - int float
char double struct.
const int degrees = 360;
const float pi = 3.14;
const char quit = 'q';
Operators
Assignment Operator – Equal sign (=)
- the most basic assignment
operator where the value on the
right of the equal sign is assigned to
the variable on the left.
Example:
c = c + 1;
radius = 2 * diameter;
stat = getch();
Operators
Binary Operators
- take two operands and return a result.

Operator Use Result


+ op1 + op2 adds op1 to op2
- op1 - op2 subtracts op2 from op1
* op1 * op2 multiplies op1 by op2
/ op1 / op2 divides op1 by op2
% op1 % op2 computes the remainder
from dividing op1
by op2
Operators
Unary Operators
- changes the sign of a value or
variable.
- Unary minus (-) and unary plus
(+)
Examples:
2 +-3
((-x) + (+y))
Operators
Increment (++) and Decrement (--)
Operators

++ increment adds one to a value of the


variable
-- decrement subtracts one from a value
of the variable

Note: The value of the expression in which


++ or -- operator is used depends on the
position of the operator.
Increment (++) and Decrement(--) Operators

 Prefix increment
 is when the ++ is placed immediately
in front of its operand.
 the value of the expression is the
variable’s value after incrementing.
Increment (++) and Decrement(--) Operators

 Postfix increment
 is when the expression’s value is the
value of the variable before it is
incremented.
Increment (++) and Decrement(--) Operators

 Comparison of POSTFIX and PREFIX


Increments
 Before… x y
Increment (++) and Decrement(--) Operators
 Increments… y = ++x y = x++
 Prefix: Increment x and then used
it.
 Postfix: Use x and then increment
it.

 Prefix Postfix
 After… x y x y
Example
main(){
int a=3, b;

b=a++;
printf(“b is %d, and a is %d\n”, b, a);
b=++a;
printf(“Now b is %d, and a is %d\n”, b, a);
b=5%--a;
printf(“Now b is %d, and a is %d\n”, b, a);
printf(“Now b is %d, and a is %d\n”, ++b, a--);
printf(“Now b is %d, and a is %d\n”, b, a);
}
Output
b is 3, and a is 4
Now b is 5, and a is 5
Now b is 1, and a is 4
Now b is 2, and a is 4
Now b is 2, and a is 3
Operators
Prefix increment/decrement - when the ++
or -- is placed immediately in front of its
operand. Meaning the value of the
expression is the variables value after
incrementing or decrementing.

Postfix increment/decrement – when the


++ or -- comes immediately after the
operand. The value of the expression is
the value of the variable before it is
incremented or decremented.
Predefined Mathematical Functions
Function Purpose
abs(x) returns the absolute value of integer x.
x=abs(-5); x=5
fabs(x) returns the absolute valued of type double.
x=fabs(-5.2); x=5.2
ceil(x) rounds up or returns the smallest whole
number that is not less than x.
x=ceil(5.2); x=6
floor(x) rounds down or returns the largest whole
number that is not greater than x.
x=floor(5.2); x=5
Predefined Mathematical Functions
Function Purpose
sqrt(x) returns the non-negative square of x.
x=sqrt(25); x=5
pow(x) returns x to the power of y.
x=pow(4,2);x=16
sin(x) returns the sine of angle x.
cos(x) returns the cosine of angle x.
tan(x) returns the tangent of angle x.
log(x) returns the natural logarithm of x.
log10(x) returns the base 10 logarithm of x.
Conversion Specifications
Date Types printf conversion scanf conversion
specification specifications
long double %Lf %Lf
double %f %lf
float %f %f
unsigned long int %lu %lu
long int %ld %ld
unsigned int %u %u
int %d %d
short %hd %hd
char %c %c
I/O Functions
Numeric Input Command

scanf() – one of the Turbo C object stream


object that is used to accept data from the
standard input, usually the keyboard.
syntax:
scanf(“format”, &var_name);
Example:
printf(“Input side of the square:”);
scanf(“%d”, &s);
Note
A terminal keyboard and monitor can be associated
only with a text stream. A keyboard is a source
for a text stream; a monitor is a destination
for a text stream.
Note
scanf requires variable addresses in the address list.
I/O Functions
Character/String Input Command

getch() – allows the user to input a


character and wait for the enter key.
Inputted char will not be echoed but could
be stored if location is specified.
Syntax:
getch();
var_name = getch();

Example: ans = getch();


I/O Functions
Character/String Input Command

getche() – allows the user to input a


character and there is no need for the enter
key. Inputted char will be echoed but could
be stored if location is specified.
Syntax:
getche();
var_name = getche();

Example: ans = getche();


I/O Functions
Character/String Input Command

gets() – allows the user to input a sequence


of characters (string).
syntax:
gets(variable_name_of_char_type);

Example:
gets(name);
I/O Functions
Output Command

printf – writes formatted output to the standard output device such as the
monitor.
syntax:
printf(“format code”,var_name);
Example:
printf(“%d”,x);

puts – writes the string to the standard output device such as the monitor and
positions the cursor to the next line.
syntax:
puts(“string expression”);
Example: puts(“CIT”);
FIGURE 2-17 Output Stream Formatting Example
I/O Functions
Output Command

putchar – writes the single character to


the screen.
syntax:
putchar(var_name);

Example:
putchar(a);
Introduction to C Programming

CONTROL FLOW
Control Flow
Control Structures - specify the sequence of
execution of a group of statements.
3 Types:

1. Sequential

2. Conditional

3. Iterative
Control Flow
1. Sequential Logic Structure

- The oldest logic structure


- The most used logic structure
- The easiest structure to understand
- Is one statement after another
statement, after another statement,
after another statement, etc.
FLOWCHART

A flowchart is a diagrammatic representation that


illustrates the sequence of operations to be
performed 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. documentation of a complex
program.
Flowchart
Flowcharting is a technique of
showing logical flow of data in
pictorial form and integration
of programming steps for
solving a given problem.
Program Flowchart
The flowchart is a means of visually presenting the flow of data through an
information processing systems, the operations performed within the system and the
sequence in which they are performed. In this topic, the concentration will be that of
a program flowchart, which describes what operations (and in what sequence) are
required to solve a given problem. The program flowchart can be likened to the
blueprint of a building. As we know a designer draws a blueprint before starting
construction on a building. Similarly, a programmer prefers to draw a flowchart prior
to writing a computer program. As in the case of the drawing of a blueprint, the
flowchart is drawn according to defined rules and using standard flowchart symbols
prescribed by the American National Standard Institute, Inc.
Guidelines in Flowcharting
1. In drawing a proper flowchart, all necessary
requirements should be listed in logical order.
2. Flowchart should be clear, neat and easy to follow.
3. The usual direction of the flow of a procedure or
system is from left to right or top to bottom.
4. Only one flow line should come out from a process
symbol.
Guidelines in Flowcharting
5. Only one flow line should enter a decision symbol, but
2 or more flow lines, one for each possible answer,
should leave the decision symbol.
6. If flowchart becomes complex, it is better to use
connector symbols to reduce the number of flow lines.
Avoid the intersection of flow lines.
7. Ensure that flowchart has a logical start and end.
8. It is useful to test the validity of the flowchart by
passing through it with a simple test data.
Advantages of Flowchart
1. Communication
flowcharts are better way of communicating the logic
of a system to all concerned.
2. Effective analysis
with the help of flowchart, problem can be analyzed
in more effective way.
3. Proper documentation
flowcharts serve as a good program documentation.
Advantages of Flowchart
4. Efficient coding
flowcharts act as a guide or blueprint during the system
analysis and program development phase.
5. Proper Debugging
flowchart helps in debugging process
6. Efficient program maintenance
maintenance becomes easy with. It helps the
programmer to put efforts more efficiently on that part.
Limitations of Flowcharts
1. Complex logic – sometimes the logic is quite
complicated, which makes flowchart becomes
complex and clumsy.
2. Alteration and Modifications – if alterations are
required, the flowchart may require re-drawing
completely.
3. Reproduction – flowchart symbols cannot be typed,
reproduction of flowchart becomes a problem.
4. The essentials of what is done can easily be lost in the
technical details of how it is done.
Algorithms and Flowcharting
Flowchart Symbols:

1. Terminal Symbol
- used to designate the beginning and end of a
program.
2. Input Symbol or
- represents an instruction to an input device
3. Processing Symbol
- used to represent a group of program instructions
that perform a processing function or activity such
as mathematical operations or logical comparisons.
Algorithms and Flowcharting
Flowchart Symbols:

4. Output Symbol or
- represents an instruction to an output device.
5. Decision Symbol
- denotes a point in the program where more
than one path can be taken or used to
designate a decision making process.
Algorithms and Flowcharting
Flowchart Symbols:

6. Flow lines and Arrowheads


- used to show reading order or sequence in which
flowchart symbols are to be lead.
- show the direction of processing of data flows.
7. On-page Connector
- non processing symbol
- used to connect one part of the flowchart to another without
drawing flow lines within page.
Denotes an
Denotes an
A exit
entry A
Algorithms and Flowcharting
Flowchart Symbols:
8. Off-page Connector
- non processing symbol
- used to connect one part of the flowchart to another
without drawing flow lines not within the same page.

9. Predetermined Symbol
- used as a subroutine symbol
- inner procedure needs to be repeated
several times.
Flowchart Symbols:
10. Preparation/Initialization Symbol
Most Commonly Used Symbol
Flowchart (Applications)
Sequential/Linear Flowchart
Sequential/Linear Flowchart
Sequential/Linear Flowchart
Sample Flowchart
Sample Flowchart
Sample Flowchart
Sample Flowchart
System Flowcharts

A system flowchart shows in general


terms the operations that will be
performed on information in an
information system. The arrows on a
system flowchart show the direction that
data will flow in around the system rather
than the order in which the operations will
be carried out.
System Flowchart Symbols
System Flowchart Example : Car Repair Garage
OTHER TYPES OF FLOWCHARTS

High-Level Flowchart
A high-level (also called first-level or top-down) flowchart shows the major steps in a process. It
illustrates a "birds-eye view" of a process, such as the example in the figure entitled High-Level
Flowchart of Prenatal Care. It can also include the intermediate outputs of each step (the product or
service produced), and the sub-steps involved. Such a flowchart offers a basic picture of the process
and identifies the changes taking place within the process. It is significantly useful for identifying
appropriate team members (those who are involved in the process) and for developing indicators for
monitoring the process because of its focus on intermediate outputs.
Most processes can be adequately portrayed in four or five boxes that represent the major steps or
activities of the process. In fact, it is a good idea to use only a few boxes, because doing so forces
one to consider the most important steps. Other steps are usually sub-steps of the more important
ones.
Detailed Flowchart

The detailed flowchart provides a detailed picture of a process by


mapping all of the steps and activities that occur in the process. This type
of flowchart indicates the steps or activities of a process and includes
such things as decision points, waiting periods, tasks that frequently must
be redone (rework), and feedback loops. This type of flowchart is useful
for examining areas of the process in detail and for looking for problems
or areas of inefficiency. For example, the Detailed Flowchart of Patient
Registration reveals the delays that result when the record clerk and
clinical officer are not available to assist clients.
Sample Problem

1. Make a flowchart that will input the length and width of a


rectangle. Output the perimeter.
2. Make a flowchart that will compute for the area of a circle
given a radius of 9 cm.
3. Make a flowchart that will ask the user to input the radius
of a circle. compute for the area of a circle and output it.
Sample Problem
4. Make a flowchart that will input 2 integers and will
output the sum, difference, product and qoutient of
the 2 integers.

5. A certain store sells softdrinks for P 6.00 and


sandwiches for P 6.50. Draw the flowchart to input
the number of softdrinks and sandwiches bought and
output the bill.
Sample Problem
A certain store sells softdrinks for P 6.00
5-1.
and sandwiches for P 6.50. Draw the flowchart
to input the number of softdrinks and
sandwiches bought and output the bill. Assume
that your program will ask the buyer to input
amount to pay. OUtput the change to given to
the buyer.
Sample Problem
6. Make a flowchart that will prompt the user to input the base
and the height of a triangle. Output the computed area of a
triangle.

7. Make a flowchart that will input a measurement in meters and


output the equivalent measurement in inches.

8.Make a flowchart that will input the area of a circle. Determine


the diameter of the circle.
Sample Problem

8.Make a flowchart and a C Program that will


input the area of a circle. Determine the
diameter of the circle.
Sample Problem
9. A salesman in XYZ company is selling toothpaste for
P89.75 each and tooth powder for P155.95 each. The
salesman will have a 10% commission on the sale of
toothpaste and 20% commission on tooth powder.
Draw a flowchart and a C Program to input the name of
the salesman, the number of toothpaste and tooth
powder he sells. Output the name of the salesman, the
total sale and the total commission he earned.
Sample Problem
10. Make a flowchart and a C Program that will
compute for the distance between 2 points A
and B. The user is asked to input the values of
points A(x1,y1) and B(x2,y2). Output the
following:
a] distance between the 2 points
b] slope of the line
Sample Problem
11.Max wants to borrow P50,500.00 in a bank to
put up a small business. The bank gives a rate of 9.5
percent for a 6 year period of time. Compute for the
interest that Max will pay after 6 years? Output the
computed interest. Draw the flowchart and make a
C Program.
Sample Problem
12. Make a flowchart to input a radius and will compute for
the area and volume of a sphere (surface). Output the
computed area and volume.

Area = 4 × pi × radius2
Volume= 3/4 × pi × radius3.
Sample Problem
13. Make a flowchart and a C program to input
2 integers. If the 1st integer is greater than the
nd
2 integer, compute the sum of the 2
integers, otherwise compute the product.
Output the sum or product of the 2 integers.
Sample Problem
13. Any customer whose total PURCHASE
is at least P1000 will be given a 10%
discount. Make a flowchart that would
input the customer’s PURCHASE and
output his net BILL.
Computer Programming 1

THE END
PART A
Computer Programming 1

Prepared by:

Roel Lauron
Instructional Resources/ Textbook

References:
005.133/B789/2013 Bronson, Gary J. C++ Programming: Principles and Practices for Scientists and Engineers. Cengage
Learning, 2013.

005.133/F769/2011 Forouzan, Behrouz A. Foundations of C Programming. Cengage Learning, 2011.

005.133/M295/2011 Malik, D.S. C++ Programming: Problem Analysis to Program Design. Cengage Learning, 2011.

005.133/Sch644/2011 Scholl, T., Nugent, G. C++ Programming Problem Analysis to Program Design (Lab Manual). Cengage
Learning, 2011

005.133/V74/2008 Vine, Micheal A. C Programming for the Absolute Beginner, 2008


Internet Sources:

www.course.com
www.thomsonlearning.com
www.tutorialspoint.com/cprogramming/
www.cprogramming.com/tutorial/c-tutorial.html
www.iu.hio.no/~mark/CTutorial/CTutorial.html
http://fresh2refresh.com/c-tutorial-for-beginners
Sample Problem
Write a C program to input an amount (integer value) and break
the amount into smallest possible number of bank notes.
Test Data :
Input the amount: 375
There are:
3 Note(s) of 100.00
1 Note(s) of 50.00
1 Note(s) of 20.00
1 Note(s) of 5.00
Sample Problem

13. Make a flowchart that


will input an integer. Print
the number if it’s POSTIVE.
Control Flow
1. Sequential Logic Structure

- The oldest logic structure


- The most used logic structure
- The easiest structure to understand
- Is one statement after another
statement, after another statement,
after another statement, etc.
Most Commonly Used Symbol
Conversion Specifications
Date Types printf conversion scanf conversion
specification specifications
long double %Lf %Lf
double %f %lf
float %f %f
unsigned long int %lu %lu
long int %ld %ld
unsigned int %u %u
int %d %d
short %hd %hd
char %c %c
Variables, Data Types and Constants
Type Bytes Bits Range
short int 2 16 -32,768 -> +32,767 (32kb)
unsigned short int 2 16 0 -> +65,535 (64Kb)
unsigned int 4 32 0 -> +4,294,967,295 ( 4Gb)
int 4 32 -2,147,483,648 -> +2,147,483,647 (2Gb)
long int 4 32 -2,147,483,648 -> +2,147,483,647 (2Gb)
signed char 1 8 -128 -> +127
unsigned char 1 8 0 -> +255
float 4 32
double 8 64
long double 12 96
Sequential/Linear Flowchart
#include<stdio.h>
#include<conio.h>

int main()
{
int x, y, total=0; //declaration part
printf("Enter value of x:");
scanf("%d", &x);
printf("Enter value of y:");
scanf("%d", &y);
total=x+y;
printf(“The sum is %d", total);
return 0;
}
Sequential/Linear Flowchart
#include<stdio.h>
#include<conio.h>

int main()
{
int x, y, total=0; //declaration part
float ave=0.0;
printf("Enter values of x and y separated by space:");
scanf("%d %d", &x, &y);
total=x+y;
ave=(float) total/2; //typecasting
printf(“The average is %0.2f", ave);
return 0;
}
Sequential/Linear Flowchart
#include<stdio.h>
#include<conio.h>

int main()
{
int x, y, total=0; //declaration part
float ave=0.0;
printf("Enter value of x:");
scanf("%d", &x);
printf("Enter value of y:");
scanf("%d", &y);
total=x+y;
ave=(float) total/2; //typecasting
printf(“The average is %0.2f", ave);
return 0;
}
Sequential/Linear Flowchart
#include<stdio.h>
#include<conio.h>

int main()
{
int x, y, total=0; //declaration part
float ave=0.0;
printf("Enter values of x and y separated by space:");
scanf("%d %d", &x, &y);
total=x+y;
ave=(float) total/2; //typecasting
printf(“The average is %0.2f", ave);
return 0;
}
Sequential/Linear Flowchart
Problem: Make a FC and a C program to input
radius of a circle. Output the computed area
and circumference of the circle. #include<stdio.h>
#include<conio.h>

int main()
{
int rad; //declaration part
float area_circ=0.0, circum=0.0, pi=3.1416;
printf("Enter radius of a circle:");
scanf("%d", &rad);
area_circ=pi*rad*rad; //computations done here
circum=2*pi*rad;
printf(“The area of the circle is %0.2f", area_circ);
printf(“\nThe circumference of the circle is %0.2f”, circum;);
return 0;
}
Sequential/Linear Flowchart
Problem: Make a FC and a C program to input
radius of a circle. Output the computed area
and circumference of the circle. #include<stdio.h>
#include<conio.h>
#define PI 3.1416

int main()
{
int rad; //declaration part
float area_circ=0.0, circum=0.0;
printf("Enter radius of a circle:");
scanf("%d", &rad);
area_circ=PI*rad*rad; //computations done here
circum=2*PI*rad;
printf(“The area of the circle is %0.2f", area_circ);
printf(“\nThe circumference of the circle is %0.2f”, circum;);
return 0;
}
Sequential/Linear Flowchart

#include<stdio.h>
#include<conio.h>
Problem:
Make a C program to int main()
{
input your name and int age;
char name[20];
age. Output your name printf("Enter your name:");
and age in 1 line. gets(name);
printf("Enter your age:");
scanf("%d", &age);
printf("Name:%s \tAge:%d", name, age);
return 0;
}
Sequential/Linear Flowchart
#include<stdio.h>
#include<conio.h>
// Make a C program to compute the total bill of 2 viands
Problem: main()
{ float price1, price2, tot_bill=0; //declaration part
Make a C program to char viand1[20], viand2[20];
printf("Enter name viand1:"); //executable part

input 2 names of viand gets(viand1);


printf("Enter price viand1:");
scanf("%f", &price1);
and their corresponding fflush(stdin); //to clear (or flush) the output buffer and move the buffered data to console
printf("Enter name viand2:");
prices. Output the total gets(viand2);
printf("Enter price viand2:");
bill to be paid. scanf("%f", &price2);
tot_bill=price1 + price2; //computation or process here
//output here
printf("Total amount to be paid is:%0.2f", tot_bill);
return 0;
}
Sequential/Linear Flowchart
#include<stdio.h>
#include<conio.h>
// Make a C program to compute the total bill of 2 viands
Problem: main()
{ float price1, price2, tot_bill=0; //declaration part
Make a C program to input char viand1[20], viand2[20];
printf("Enter name viand1:"); //executable part
2 names of viand and their gets(viand1);
printf("Enter price viand1:");
corresponding prices. scanf("%f", &price1);
fflush(stdin); //to clear (or flush) the output buffer and move the buffered data to console
Output the total bill to be printf("Enter name viand2:");
gets(viand2);
paid and the change ot be printf("Enter price viand2:");
scanf("%f", &price2);
received assuming it will tot_bill=price1 + price2; //computation or process here
//output here
ask how much you are printf("Total amount to be paid is:%0.2f", tot_bill);
return 0;
going to pay. }
Sequential/Linear Flowchart
#include<stdio.h>
#include<conio.h>
// Make a C program to input 5 digit numbers. Output the number in
Problem: reverse order
Make a C program to input 5 int main()
{
digit number. Output the int num, dig1=0, dig2=0, dig3=0, dig4=0, dig5=0;
printf("Enter a 5 digit number:");
number in reverse order. scanf("%d", &num);
Example: dig1=num/10000;
dig2=(num%10000)/1000;
Enter 5 digit number:96753 dig3=((num%10000)%1000)/100;
dig4=(((num%10000)%1000)%100)/10;
35769 dig5=(((num%10000)%1000)%100)%10;
// to print in reverse order
printf("%d%d%d%d%d", dig5, dig4, dig3, dig2, dig1);
return 0;
}
Sequential/Linear Flowchart
#include<stdio.h>
#include<conio.h>
//Write a C program to convert specified days into years, weeks and days.
Problem: //Note: Ignore leap year.
Write a C program to convert int main()
specified days into years, {
int days, years, weeks;
weeks and days. printf("Enter number of days:");
scanf("%d", &days);
Note: Ignore leap year. // Converts days to years, weeks and days
Example: years = days/365; //compute for number of years
weeks = (days % 365)/7; //compute for number of week
Enter number of days:1329 days = days- ((years*365) + (weeks*7)); //remaining days
Years: 3 printf("Years: %d\n", years);
printf("Weeks: %d\n", weeks);
Weeks: 33 printf("Days: %d \n", days);
Days: 3 return 0;
}
Sequential/Linear Flowchart
#include<stdio.h>

Problem: int main()


What will be printed {
when the sample code int i = 4, x = 6; z = 0.00
below is executed? float z = 0; z = 1.00
z = (float) x / i; z = 1.50
printf(z = %0.2f\n”, z); z = 2.00
return 0;
}
Sample Problem

9. A salesman in XYZ company is selling toothpaste for P89.75 each


and tooth powder for P155.95 each. The salesman will have a 10%
commission on the sale of toothpaste and 20% commission on
tooth powder.
Draw a flowchart to input the name of the salesman, the number of
toothpaste and tooth powder he sells. Output the name of the
salesman, the total sale and the total commission he earned.
Sample Problem

10. Make a flowchart that will compute for the


distance between 2 points A and B. The user
is asked to input the values of points A(x1,y1)
and B(x2,y2). Output the computed distance.
Sample Problem

13. Make a flowchart that will


input an integer. Print the
number if it’s POSTIVE.
Control Flow
The problem now involves a condition to determine if the
inputted integer is positive or not. In this case, this kind of
problem is not anymore sequential, you need to have a
condition to determine if the number is positive. This kind
of problem is a conditional structure.
Control Flow
2. Conditional Control Structure - organized in such a
way that there is always a condition that has to be
evaluated first. The condition will either evaluate to a
true or false.

2 Types:

1. if statement (including if-else and nested if)

2. switch case statement


Operators
Conditional Operators
- expressions that evaluates to true or false.

Operator Use Result


> op1 > op2 true if op1 is greater than op2
>= op1 >= op2 true if op1 is greater or equal to op2
< op1 < op2 true if op1 is less than op2
<= op1 <= op2 true if op1 is less or equal to op2
== op1 == op2 true if op1 is equal to op2
!= op1 != op2 true if op1 is not equal to op2
Selection/Conditional Structure
Operators
Logical Operators

- used in boolean expressions and consists of logical “and", “or" and “not".
0-> false and 1-> true or nonzero digit

Operator Use Result


&& op1 && op2 true if op1 and op2 are both true

|| op1 || op2 true if either op1 or op2 is true

! !op1 op1 is false if its original value is true and vice versa
Control Flow
if Selection Structure
- performs an indicated action only when the condition is
true, otherwise the action is skipped.
Syntax: if (<expression>)
<statement>
Example:
Write a program that will allow the user to input an integer value. If the value
is greater than or equal to zero, print the word “POSITIVE”.
Begin

num

if num>0 “POSITIVE”

End
Solution
#include<stdio.h>
#include<conio.h>

int main()
{
int num;
printf("Enter a number:");
scanf("%d", &num);
if(num>0)
printf(“Number %d is POSITIVE", num);
return 0;
}
Sample Problems
1. Make a flowchart and write a C program that will allow
the user to input an integer value. If the value is greater than
or equal to zero, print the word “POSITIVE.

2. Make a flowchart and write a C program to input an


integer. Output the integer if it is a positive integer
3. Make a C program to input a number. Output the
number if it is an even number.
Solution
#include<stdio.h>
#include<conio.h>

int main()
{
int num;
printf("Enter a number:");
scanf("%d", &num);
if(num>0)
printf(“%d", num);
return 0;
}
Sample Problems
3. Make a flowchart and write a C program to input two
integers. Thereafter, the program should determine if
these two numbers are equivalent. If they are equivalent,
print the word EQUIVALENT.

4. Make a flowchart and write a C program to input two


integers. Compute the average of the 2 integers. Output
the average if it is greater than 85.
Sample Problems
CHALLENGE PROBLEM

Make a flowchart and write a C program to input


two bits number. If the sum of the 2 digit number
is ODD, print the SUM.
Ex1: Ex2:
Input 2 digit number:27 Input 2 digit number:48
Sum=9 (no output)
Solution 4 #include<stdio.h>
#include<conio.h>

int main()
{
int num1, num2, sum=0;
float ave=0.0;
printf("Enter a number1:");
scanf("%d", &num1);
printf("Enter a number2:");
scanf("%d", &num2);
sum=num1+num2;
ave=(float) sum/2; //typcasting
if(ave>85.0)
printf(“The average %0.2f is greater than or equal to 85.0", ave);
return 0;
}
Sample Problem

14.Make a flowchart and a C


program that will input an
integer. Determine if the number
is ODD or EVEN.
Control Flow
if-else Selection Structure
- allows the programmer to specify that different actions are
to be performed when the condition is true and when the
condition is false.
- If condition evaluates to true, then statementT is executed
and statementF is skipped; otherwise, statementT is skipped
and statementF is executed.
Control Flow

Syntax:
if (condition) Condition T Statement
statementT;
else F
statementF; Statement
Good Programming Practice

Indent both body statements of


an if...else statement.

If there are several levels of


indentation, each level should be
indented the same additional amount
of space.
Sample Problems
Problems:
1. Make a flowchart and write a C program that will allow the
user to input an integer value. If the value is greater than or
equal to zero, print the word “POSITIVE” else print the word
“NEGATIVE”.

2. Make a flowchart and write a C program that will input an


integer and determine if it is an even or odd number.
Solution #include<stdio.h>
#include<conio.h>

int main()
{
int num;
printf("Enter a number:");
scanf("%d", &num);
if(num<0)
{printf(“Number %d is NEGATIVE", num)};
else
printf((“Number %d is POSITIVE", num);
return 0;
}
Solution #include<stdio.h>
#include<conio.h>

int main()
{
int num;
printf("Enter a number:");
scanf("%d", &num);
if(num%2==0)
printf(“%d is EVEN", num);
else
printf((“%d is ODD", num);
return 0;
}
Solution #include<stdio.h>
#include<conio.h>

int main()
{
int num, rem=0;
printf("Enter a number:");
scanf("%d", &num);
rem=num%2;
if(rem==0)
printf(“%d is EVEN", num);
else
printf((“%d is ODD", num);
return 0;
}
Sample Problems
3. Make a flowchart and write a C program that will allow the
user to input a score and name of a student. If the score is
greater than or equal to 50 output the message
“Congratulations! You Pass” and the name of the student,
otherwise output the message “Sorry! You Fail” and the name
of the student.

4. Make a flowchart and write a C program to input an integer.


Determine if the integer is Positive or Negative.
Solution
#include<stdio.h>
#include<conio.h>

int main()
{
int num;
printf("Enter a number:");
scanf("%d", &num);
if(num>0)
printf(“Number %d is POSITIVE", num);
else
printf(“Number %d is NEGATIVE”, num);
return 0;
}
Sample Problems
5. In order to discourage excess electric consumption, an electrical
company charges its customers a lower rate of P7.5 for each of the
first 250 kilowatt-hours and a higher rate of P8.5 for each
additional kilowatt-hour. In addition, a 10% surtax is added to the
final bill. Make a flowchart and write a C program that calculates
the electrical bill given the number of kilowatt-hours consumed as
input. At the end, print the number of kilowatt-hours consumed
and the computed bill.
Solution #include<stdio.h>
#include<conio.h>
#define LOWER_FEE 7.50
#define HIGHER_FEE 8.50
int main()
{
int kw_hr, excess=0;
float tmp_bill=0, tot_bill=0,;
printf("Enter kilowatt hour consumed:");
scanf("%d", &kw_hr);
if(kw_hr<=250)
{
tmp_bill=kw_hr*LOWER_FEE;
tot_bill=tmp_bill*0.10 + tmp_bill;
}
else
{
excess=kw_hr-250;
tmp_bill=excess*HIGHER_FEE;
tot_bill=(250*LOWER_FEE+tmp_bill)*0.10+ (250*LOWER_FEE+tmp_bill);
}
printf(“%d kilowatt hour = %0.2f", kw_hr, tot_bill);
return 0;
}
Sample Problems
6. Make a flowchart and a C program to
input an integer. If the integer is divisible
by 3 and 5, change its value so that it is
now 3 times the integer plus 7,
otherwise change its value to half.
Sample Problems
7. Make a flowchart and write a C program to input a
character (lower case/upper case). Determine whether
the inputted character is Vowel or Consonant.
Ex1. Ex2.
Enter a chracter: a Enter a character: B
a is a Vowel B is Consonant
Sample Problems
8. Make a flowchart and write a C program to input 3
angles of a triangle and check whether a triangle can
be formed by the given value for the angles.

Test Data 1 Test Data 2


Enter 3 angles of a triangle: 40 55 65 Enter 3 angles of a triangle: 75 55 50
The triangle is INVALID The triangle is VALID
Sample Problems
9. Write a C program to input name of student and
marks of three subjects Math, Science and English. The
student can be admitted if the average in Math and
Science is greater than the average in Science and
English. Output the name of the student the average in
Math and Science and the average in Science and
English. Ouput also if the student is admitted/accepted
or not.
Sample Problems
CHALLENGE
10. Make a flowchart and a C program given a
circle with the centre (xc, yc) and with the
radius (rad) and will determine whether a
point (xp, yp) is inside the circle or not?
Sample Problems
11. A taxi charges P1.50 for the first 300 meters
and P1 for every 200 meters thereafter. Any
distance covering the next 200 meter zone is still
charged P1. Make a flowchart and a C program
that would input the DISTANCE a trip took and
output the FEE.
Problem 1
12.Make a flowchart and a C program to relate 2 integers entered by the user using
equal (==), less than (<) or greater than (>)

Sample output simulation


Enter 2 integers: 5 3
Result: 5 > 3

Enter 2 integers: 10 10
Result: 10 = 10
Control Flow
if-else (multiple alternatives)
- The conditions in a multiple-alternative decision are
evaluated in sequence until a true condition is reached. If a
condition is true, the statement following it is executed, and
the rest of the multiple-alternative decision is skipped. If a
condition is false, the statement following it is skipped, and
the condition next is tested. If all conditions are false, then
the statement following the final else is executed.
Control Flow
Syntax:
if (condition) Condition T Statement
statement;
F
else if (condition) T Statement
Condition
statement;
F
else if (condition)
Condition T Statement
statement;
F
else
Statement
statement;
Problem 1
Make a flowchart and a C program to relate 2 integers entered by the user using
equal (=), less than (<) or greater than (>)

Sample output simulation


Enter 2 integers: 5 3
Result: 5 > 3

Enter 2 integers: 10 10
Result: 10 = 10
Solution
#include<stdio.h>
#include<conio.h>

int main()
{
int num1, num2;
printf("Enter 2 numbers separated by space:");
scanf("%d %d", &num1, &num2);
if(num1>num2)
printf("\nNum1=%d > Num2=%d", num1, num2);
else if(num1<num2)
printf("\nNum1=%d < Num2=%d", num1, num2);
else
printf("\nNum1=%d = Num2=%d", num1, num2);
return 0;
}
Problem 3
Make a flowchart and a C program to input 2 numbers. The operations to
be performed will be based as shown below:

Choice Operation
1 Add the 2 numbers
2 Subtract the 2 numbers
3 Multiply the 2 numbers
4 Divide the 2 numbers
#include<stdio.h>
Solution
int main()
{
int num1, num2, sum=0, diff=0, prod=0, choice;
float quo=0.0;
printf("Enter 2 numbers separated by space:");
scanf("%d %d", &num1, &num2);
printf("Enter your choice (1-> ADD, 2-> SUBTRACT, 3->MULTIPLY, 4>DIVIDE:");
scanf("%d", &choice);
if(choice==1)
{ sum=num1+num2;
printf("\nThe sum of 2 numbers is %d", sum); }
else if(choice==2)
{ diff=num1-num2;
printf("\nThe difference between 2 numbers is %d", diff); }
else if(choice==3)
{ prod=num1*num2;
printf("\nThe product of 2 numbers is %d", prod); }
else
{ quo=(float) num1/num2; //typcasting
printf("\nThe quotient of 2 numbers is %0.2f", quo); }
return 0;
}
Problem 4
Make a flowchart and a C program to input 2 numbers. The operations to be performed
will be based as shown below:

Choice Operation
+ Add the 2 numbers
- Subtract the 2 numbers
* Multiply the 2 numbers
/ Divide the 2 numbers
#include<stdio.h>
Solution
int main()
{
int num1, num2, sum=0, diff=0, prod=0;
float quo=0.0;
char choice;
printf("Enter 2 numbers separated by space:");
scanf("%d %d", &num1, &num2);
printf("Enter your choice (+-> ADD, -> SUBTRACT, *->MULTIPLY, />DIVIDE:");
choice=getche();
if(choice=='+')
{ sum=num1+num2;
printf("\nThe sum of 2 numbers is %d", sum); }
else if(choice=='-')
{ diff=num1-num2;
printf("\nThe difference between 2 numbers is %d", diff); }
else if(choice=='*')
{ prod=num1*num2;
printf("\nThe product of 2 numbers is %d", prod); }
else
{ quo=(float) num1/num2; //typcasting
printf("\nThe quotient of 2 numbers is %0.2f", quo); }
return 0;
}
Problem 5
Make a flowchart and a C program that will accept a
score and output the equivalent letter grade based
on the following conditions:
Score Letter Grade
90 – 100 A
80 – 89 B
70 – 79 C
60 – 69 D
Below 60 F
#include<stdio.h>
Solution #include<conio.h>

int main()
{
int ave_grade;
printf("Enter average grade:");
scanf("%d", &ave_grade);
if(ave_grade<60)
printf("Letter Grade = F");
else
if(ave_grade>=60 && ave_grade<70)
printf("Letter Grade = D");
else
if(ave_grade>=70 && ave_grade<80)
printf("Letter Grade = C");
else
if(ave_grade>=80 && ave_grade<90)
printf("Letter Grade = B");
else
printf("Letter Grade = A");
return 0;
}
Control Flow
Sample Problem
Make a C program that prompts the user to input 2
integers and will perform the following operations:
Choice Operation
A/a ADDITION
B/b SUBTRACTION
C/c MULTIPLICATION
D/d DIVISION
#include<stdio.h>
Solution
int main()
{
int num1, num2, sum=0, diff=0, prod=0;
float quo=0.0;
char choice;
printf("Enter 2 numbers separated by space:");
scanf("%d %d", &num1, &num2);
printf("Enter your choice (+-> ADD, -> SUBTRACT, *->MULTIPLY, />DIVIDE:");
choice=getche();
if(choice==‘A’ || choice==‘a’ )
{ sum=num1+num2;
printf("\nThe sum of 2 numbers is %d", sum); }
else if(choice==‘B’ || choice==‘b’ )
{ diff=num1-num2;
printf("\nThe difference between 2 numbers is %d", diff); }
else if(choice==‘C’ || choice==‘c’ )
{ prod=num1*num2;
printf("\nThe product of 2 numbers is %d", prod); }
else
{ quo=(float) num1/num2; //typcasting
printf("\nThe quotient of 2 numbers is %0.2f", quo); }
return 0;
}
Problem 4
Visayan Electric Company charges its customers for electricity as
shown in the table.
Make a flowchart and a C program that will enter the meter reading
and calculate the cost and print out how much is charged.

Kilowatt-Hours Cost (P)


0 to 100 150
101 to 500 150 + 0. 5 for each kwh over 100
over 500 350 + 0. 3 for each kwh above 500
Problem 5
A company selling household appliances gives commissions to its salesman
determined by the kind of product sold as well as the sales amount.
Type 1: 7% of sale or 400, whichever is more.
Type 2: 10% of sale or 900, whichever is less.
Type 3: 12% of sale.
Type 4: P250, regardless of sale price.
Make a flowchart and a C program that would input the KIND of appliance
sold (between 1-4) and the sale PRICE and output the Commission that the
salesman will receive.
Taxable Income Tax Rate
More than But less than
0 P10,000 5%
P10,000 P30,000 P500 + 10% of the Excess over P10,000
P30,000 P70,000 2,500 + 15% of the Excess over P30,000
P70,000 P140,000 8,500 + 20% of the Excess over P70,000
P140,000 P250,000 P22,500 + 25% of the Excess over P140,000
P250,000 P500,000 P50,000 + 30% of the Excess over P250,000
P500,000 P125,000 + 32% of the Excess over P500,000
Problem 6

Based from the table above, make a flowchart and a C


program to input the Net Taxable Income (Net Income
minus all the deductions) of a Filipino worker and output
the Tax Payable to the Philippine government at the end
of a fiscal year.
Problem 7

A taxi charges P1.50 for the first 300 meters and P1


for every 200 meters thereafter. Any distance
covering the next 200 meter zone is still charged
P1. Make a flowchart and a C program that would
input the DISTANCE a trip took and output the FEE.
Control Flow
 Nested-if Statement
 Syntax:
if (condition)
{
if (condition)
statement;
else
statement;
}
else
Good Programming Practice
A nested if...else statement can perform
much faster than a series of single-selection
if statements because of the possibility of
early exit after one of the conditions is
satisfied.

In a nested if...else statement, test the conditions


that are more likely to be true at the beginning of
the nested if...else statement. This will enable the
nested if...else statement to run faster and exit
earlier than testing infrequently occurring cases
first.
Good Programming Practice

Always putting the braces in an if...else statement


(or any control statement) helps prevent their
accidental omission, especially when adding
statements to an if or else clause at a later time. To
avoid omitting one or both of the braces, some
programmers prefer to type the beginning and
ending braces of blocks even before typing the
individual statements within the braces.
Common Programming Error

Forgetting one or both of the


braces that delimit a block can
lead to syntax errors or logic
errors in a program.
Common Programming Error

Placing a semicolon after the condition in


an if statement leads to a logic error in
single-selection if statements and a syntax
error in double-selection if...else
statements (when the if part contains an
actual body statement).
Control Flow

Make a flowchart and a C program that


prompts the user to input an integer. Output
the integer if it is a positive even integer.
Solution #include<stdio.h>
#include<conio.h>

int main()
{
int num;
printf("Enter a number:");
scanf("%d", &num);
if(num>0)
{
if(num%2==0)
printf("\n%d", num);
}
return 0;
}
Solution
#include<stdio.h>
#include<conio.h>

int main()
{
int num;
printf("Enter a number:");
scanf("%d", &num);
if(num>0 && num%2==0) //combine the test
printf("\n%d", num);
return 0;
}
Problem 2

Every leap year is divisible by 4. However, if a year is


divisible by 100, it must also be divisible by 400 for it
to be a leap year. Hence, 2000 is a leap year, but 1900
is not. Make a flowchart that will input a value for
YEAR (integer) and output whether it is a “LEAP YEAR”
or “NOT A LEAP YEAR”.
Ternary Operator

There is alternative to ‘if-else’ condition which is ternary operator


that is different syntax but provides functionality of ‘if-else’
condition.
Basic syntax of ternary operator is given below:

(condition expression) ? if condition is TRUE, return statement1 :


Otherwise, return statement2;
Example
#include <stdio.h>
int main()
{
int num;
printf("Enter a number:");
scanf("%d", &num);
(num%2==0) ?
printf("%d is EVEN\n", num):printf("%d is ODD\n",num);
return 0;
}
Output
Enter a number:24
24 is EVEN

Enter a number:23
23 is ODD
Control Flow

Leap years occur in years exactly divisible by


four, except that years ending in 00 are leap
years only if they are divisible by 400. Hence,
2000 is a leap year, but 1900 is not. Make a
flowchart and a C program that will input a
value for YEAR (integer) and output whether it
is a “LEAP YEAR” or “NOT A LEAP YEAR”.
Con’t Leap Year Problem

So, 1700, 1800, 1900, 2100, and


2200 are not leap years. But
1600, 2000, and 2400 are leap
years.
Control Flow

Make a C program that prompts the user to


input an integer. Output the integer if it is a
positive even integer between 20-50.
Control Flow

Switch Statement

Is a selection statement provided by C. It


has a built in multiple branch and work
similar to if else ladder generally.
Why Use Switch Case?

1. One of the classic problem encountered in nested if-else/else-if


ladder is called problem of Confusion.
2. It occurs when no matching else is available for it.
3. As the number of alternatives increases the Complexity of
program increases drastically.
Control Flow
Switch Statement
- the controlling expression, an expression with a
value of type int or type char, is evaluated and
compared to each of the case labels in the case
constant until a match is found. A case constant is
made of one or more labels of the form case
followed by a constant value and a colon.
Control Flow
When a match between the value of the controlling
expression and a case label value is found, the
statement following the case label are executed until a
break statement is encountered. Then the rest of the
switch statement is skipped. A default case is allowed
which will be executed if no other statement match is
found.
Control Flow
It is defined by C that a compiler must
support a minimum of 257 case
statements in C89 and 1023 case
statements in C99 though you may
want to keep this to minimum in
consideration of efficiency.
Control Flow
Switch Statement
Syntax:
switch (controlling expression)
{
case constant: statement;
break;
case constant: statement;
break;
. . .
default: statement;
}
Rules for Switch Statement
1. The expression used in a switch statement must have an
integral or enumerated type, or be of a class type in which
the class has a single conversion function to an integral or
enumerated type.
2. You can have any number of case statements w/in a switch.
Each case is followed by the value to be compared to and a
colon.
3. The constant-expression for a case must be the same data
type as the variable in the switch, and it must be a constant
or a literal.
Rules for Switch Statement
4. When the variable being switched on is equal to a
case, the statements following that case will execute
until a break statement is reached.
5. When a break statement is reached, the switch
terminates, and the flow of control jumps to the next
line following the switch statement.
6. Not every case needs to contain a break. If no
break appears, the flow of control will fall through to
subsequent case until a break is reached.
Rules for Switch Statement
7. A switch statement can have an
optional default case, which must
appear at the end of the switch. The
default case can be used for performing
a task when none the cases is true. No
break is needed in the default case.
Control Flow

Break

- exits from the lowest-level loop in


which it occurs.
- used for early exit from the loop, or for
exiting a forever loop
Control Flow
Continue
– causes immediate loop iteration, skipping the
rest of the loop statements
- jumps to the loop test when used with while or
do
- jumps to loop increment, then test when used
with for
- does not exit the loop (unless next loop is false)
Control Flow
Example
Make a C program that prompts the user to
input 2 integers and will perform the following
operations:
Choice Operation
1 ADDITION
2 SUBTRACTION
3 MULTIPLICATION
4 DIVIDE
#include<stdio.h>
Solution #include<conio.h>

int main()
{
int num1, num2, sum, diff, prod, choice;
printf("Enter the first number:");
scanf("%d", &num1);
printf("Enter the second number:");
scanf("%d", &num2);
printf("Enter your choice (1-> ADD, 2-> SUBTRACT, 3->MULTIPLY:");
scanf("%d", &choice);
switch(choice) {
case 1: {
sum=num1+num2;
printf("The sum of 2 numbers is %d", sum);
break;
}
case 2: {
diff=num1-num2;
printf("The difference between 2 numbers is %d", diff);
break;
}
case 3: {
prod=num1*num2;
printf("The product of 2 numbers is %d", prod);
break;
}
default:
printf("Wrong Choice!!!"); }
return 0;
}
Sample Problem
A company selling household appliances gives commissions to its salesman
determined by the kind of product sold as well as the sales amount.
Type 1: 7% of sale or 400, whichever is more.
Type 2: 10% of sale or 900, whichever is less.
Type 3: 12% of sale.
Type 4: P250, regardless of sale price.
Make a C program that would input the KIND of appliance sold (between 1-4)
and the sale PRICE and output the Commission that the salesman will
receive. (Use switch)
Control Flow
Example
Make a C program that prompts the user to
input 2 integers and will perform the following
operations:
Choice Operation
+ ADDITION
- SUBTRACTION
* MULTIPLICATION
/ DIVIDE
Control Flow
Sample Problem
Make a C program that prompts the user to input 2
integers and will perform the following operations:
(use switch)
Choice Operation
A/a ADDITION
B/b SUBTRACTION
C/c MULTIPLICATION
D/d DIVISION
#include<stdio.h>
#include<conio.h>
Solution
int main()
{
int num1, num2, sum, diff, prod;
char choice;
printf("Enter the first number:");
scanf("%d", &num1);
printf("Enter the second number:");
scanf("%d", &num2);
printf("Enter your choice (A/a-> ADD, B/b-> SUBTRACT, C/c->MULTIPLY:");
choice=getche(); //choice=getch();
switch(choice) {
case 'A’: case 'a':{
sum=num1+num2;
printf("\nThe sum of 2 numbers is %d", sum);
break;
}
case 'B': case 'b':{
diff=num1-num2;
printf("\nThe difference between 2 numbers is %d", diff);
break;
}
case 'C’: case 'c': {
prod=num1*num2;
printf("\nThe product of 2 numbers is %d", prod);
break;
}
default:
printf("\nWrong Choice!!!"); }
return 0;
}
Make a C program that will prompt the user to
input a number from 1-99 and will otput its
equivalent in words. (Use switch)

Example

Enter a 2 digit number: 2


Two

Enter a 2 digit number: 45


Forty-five
Make a C program that prompts the user to input his/her
grade point average (1.0-5.0) and will determine the type
of scholarship that he/she can avail as shown below:

GPA Scholarship Type


4.9 – 5.0 Presidential
4.7 – 4.89 College
4.5 – 4.69 Department
4.3 – 4.49 Dean’s List
Below 4.3 Dean’s Lost

Use a) Multiple if b) Switch


Make a C program that prompts the user to input his/her
average grade(0-100) and will determine the letter grade
as shown below:

Average Grade Letter Grade


90 – 100 A
80 – 89 B
70 – 79 C
60 – 69 D
Below 60 F

Use a) Multiple if b) Switch


#include<stdio.h>
Solution #include<conio.h>

int main()
{
int ave_grade;
printf("Enter average grade:");
scanf("%d", &ave_grade);
if(ave_grade<60)
printf("Letter Grade = F");
else
if(ave_grade>=60 && ave_grade<70)
printf("Letter Grade = D");
else
if(ave_grade>=70 && ave_grade<80)
printf("Letter Grade = C");
else
if(ave_grade>=80 && ave_grade<90)
printf("Letter Grade = B");
else
printf("Letter Grade = A");
return 0;
}
Solution #include<stdio.h>
#include<conio.h>

int main()
{
int ave_grade;
printf("Enter average grade:");
scanf("%d", &ave_grade);
switch(ave_grade)
{
case 0 ... 59: printf("Letter Grade = F"); break;
case 60 ... 69: printf("Letter Grade = D"); break;
case 70 ... 79: printf("Letter Grade = C"); break;
case 80 ... 89: printf("Letter Grade = B"); break;
case 90 ... 100: printf("Letter Grade = A"); break;
default: printf("Average Grade OUT of RANGE!!!");
}
return 0;
}
Given a point, a line from the point forms an angle with the horizontal
axis to the right of the line. The line is said to terminate in one of four
quadrants based on its angle (a) from the horizontal. Write a C program
determines the quadrant, given a user-input angle. Note: If the angle is
exactly 0°, it is not in a quadrant but lies on the positive X-axis; if it is
exactly 90°, it lies on the positive Y-axis; if it is exactly 180°, it lies on
the negative X-axis; and if it is exactly 270°, it lies on the negative Y-
axis.

Quadrants Angle (a)


I 0 < a < 90
II 90 < a < 180
III 180 < a <270
IV 270 < a < 360

Test Data 1 Test Data 2 Test Data 3


Input an angle: 30 Input an angle: 190 Input an angle: 310
Quadrant I Quadrant III Quadrant IV
Computer Programming 1

THE END
PART B
Computer Programming 1

Prepared by:

Roel Lauron
Instructional Resources/ Textbook

References:
005.133/B789/2013 Bronson, Gary J. C++ Programming: Principles and Practices for Scientists and Engineers. Cengage
Learning, 2013.

005.133/F769/2011 Forouzan, Behrouz A. Foundations of C Programming. Cengage Learning, 2011.

005.133/M295/2011 Malik, D.S. C++ Programming: Problem Analysis to Program Design. Cengage Learning, 2011.

005.133/Sch644/2011 Scholl, T., Nugent, G. C++ Programming Problem Analysis to Program Design (Lab Manual). Cengage
Learning, 2011

005.133/V74/2008 Vine, Micheal A. C Programming for the Absolute Beginner, 2008


Internet Sources:

www.course.com
www.thomsonlearning.com
www.tutorialspoint.com/cprogramming/
www.cprogramming.com/tutorial/c-tutorial.html
www.iu.hio.no/~mark/CTutorial/CTutorial.html
http://fresh2refresh.com/c-tutorial-for-beginners
Problem 14
Make a flowchart that will input 10
integers. Output the sum of the
inputted integers. Lots of input and
not good to see. What if we have
hundreds, thousands or even millions
of inputs? How to solve this problem?
Loops/Iteration
Question:

Why use loop or iteration?


Solution: Use Loops
3. Iteration/Loop

When is loop required?


Repeating Statement Execution

Loop is a sequence of instructions that is continually


repeated until a certain condition is reached.
It is used to repeat execution of block of code.
Execution of Loops

Typically this is done inside a loop statement of


some sort using a variable as a counter to keep
track of which character is to be checked. The
counter variable may be incremented by one,
each time through, so that the first element is
examined the first time through the loop, the
second element the second time, and so forth.
Execution of Loops

Being able to repeatedly


execute a statement or
compound statement is an
essential feature of
programming.
Loops

There are several loop types.

Depending on situation, sometimes it is


better to use one kind of loop than
another, but every loop can be
transformed into one another.
Loops

This is not so important for


beginners, you just need to
know that there is good and
better use of particular loop.
Control Flow
A loop has the following components:

1. Initialization of variables – setting an initial value of zero/one


before the loop statement is reached.
2. Condition/testing – (that would evaluate to either true or false)
the condition to check is usually made on the current value of the
variable initialized in (0/1) for it controls the loop repetition.
3. Body – statements that are repeated in the loop.
4. Updating – a statement inside the body of the loop that updates
the value of the variable that is initialized during each repetition.
Control Flow

3 Types:

1. do-while statement
2. while statement
3. for statement
Control Flow

do-while statement

- This loop executes a block of codes as long as


the specified condition is true.
- It is a post checked loop because it checks the
controlling condition after the code is executed.
Control Flow
Syntax:
do
{
statement/s;
} while (loop repetition condition);

Example:
c=1;
do
{
printf(“Hello World\n”);
c++; //c=c+1; c+=1
} while (c<=5);
Sample Problems: Implement using do while
#include<stdio.h>
#include<conio.h>
//Make a C program to input 10 integers and will output their sum
Problem 1
int main()
{
Make a C program that int num, ctr=1, sum=0; //declaration part
will input 10 numbers. do
{
Output the sum. printf("Enter number%d:", ctr);
scanf("%d", &num);
sum=sum+num; //can be written also as sum+=sum;
ctr=ctr+1; //can be written aslo as ctr++;
} while(ctr<=10);
printf("The sum is %d", sum);
return 0;
}
Sample Problems: Implement using do while
#include<stdio.h>
#include<conio.h>
//Make a C program to input 10 integers and will output their sum
Problem 1
int main()
{
Make a C program that int num, ctr=10, sum=0; //declaration part
will input 10 numbers. do
{
Output the sum. printf("Enter number%d:", ctr);
scanf("%d", &num);
sum=sum+num; //can be written also as sum+=sum;
ctr=ctr-1; //can be written aslo as ctr--;
} while(ctr>=1);
printf("The sum is %d", sum);
return 0;
}
Sample Problems: Implement using do while
#include<stdio.h>
#include<conio.h>
//Make a C program to input 10 integers and will output their sum
Problem 1
int main()
{
Make a C program that int num, ctr=0, sum=0; //declaration part
will input 10 numbers. do
{
Output the sum. printf("Enter number%d:", ctr);
scanf("%d", &num);
sum=sum+num; //can be written also as sum+=sum;
ctr=ctr+1; //can be written aslo as ctr++;
} while(ctr<10);
printf("The sum is %d", sum);
return 0;
}
Sample Problems: Implement using do while
#include<stdio.h>

int main()
{
Problem 2 int ctr=1, num, ctr_E=0, ctr_O=0; //initialization
do
{
Make a C program that printf("Enter number%d:", ctr);
will input 10 numbers. scanf("%d", &num);
//process
Output how many odd if(num%2==0)
and how many even ctr_E=ctr_E+1;
else
numbers are there. ctr_O=ctr_O+1;
ctr++; //c=c+1; c+=1, updates
} while (ctr<=10); //test
printf("There are %d EVEN and %d ODD" , ctr_E, ctr_O);
return 0;
}
Sample Problems: Implement using do while
#include<stdio.h>

Problem 3 int main()


{
Write a C program to int ctr=1;
do
display the first 10
{
natural numbers. printf("\n%d ", ctr);
ctr++;
} while(ctr<=10);
return 0;
}
Sample Problems: Implement using do while
#include<stdio.h>

int main()
Problem 4 {
int ctr=1;
Make a C program to char name[20];
input your name and printf("Enter your name:");
gets(name);
will print it 10 times. do
{
printf("%s\n ", name);
ctr++;
} while(ctr<=10);
return 0;
}
Sample Problems: Implement using do while
int main()
{
int num, ctr=1, ctr_pos_odd=0, sum_pos_odd=0; //declaration part
Problem 5 float ave_pos_odd=0.0;
do
{ printf("Enter number%d:", ctr);
scanf("%d", &num);
Make a C program if(num>0 && num%2!=0)
{ sum_pos_odd+=num;
to input 10 integers }
ctr_pos_odd++;

and will output the ctr=ctr+1; //can be written also as ctr++;


} while(ctr<=10);
average of all if(ctr_pos_odd==0)
printf(“The average is 0!”);
else
positive odd {
ave_pos_odd=(float) sum_pos_odd/ctr_pos_odd; //typecasting
integers. printf("The average of all positive odd integer is %0.2f", ave_pos_odd);
}
return 0;
}
Sample Problems: Implement using do while
#include<stdio.h>

Problem 6 int main()


{
Make a C program to
int num, ctr=1;
input a number. Output printf("Enter a number:");
all the factors of the scanf("%d", &num);
number excluding itself. do
{
Sample output: if(num%ctr==0)
Enter an integer: 6 printf("%d ",ctr);
Factors are: 1 2 3 ctr++;
} while(ctr<num);
return 0;
}
Sample Problems: Implement using do while
int main()
Problem 5 {
int num,
return 0;
Make a C program }

to input a number.
Determine
whether the
number if PRIME
or COMPOSITE.
Sample Problems: Implement using do while
#include<stdio.h>
Problem 6
A Perfect number, a int main()
positive integer that is {
int num, ctr=1, sum_factor=0;
equal to the sum of its printf("Enter a number:");
proper divisors. The scanf("%d", &num);
do
smallest perfect number is
{
6, which is the sum of 1, 2, if(num%ctr==0)
and 3. Other perfect sum_factor+=ctr;
ctr++;
numbers are 28, 496, and } while(ctr<num);
8,128. Make a C program to if(cum_factor==num)
input an inetger and will printf(“%d is a Perfect number!”, num);
else
determine if it’s Perfect printf(“%d is OT a Perfect number!”, num);
number or not. r eturn 0;
}
Sample Problems: Implement using do while Version1
#include<stdio.h>
Problem 7
int main()
Make a C program that {
will input integers. The int num, sum=0;
do
program terminates if a {
negative number is printf("Enter a number:");
inputted. Output the scanf("%d", &num);
sum of all inputted if(num>0)
sum+=num; //sum=sum+num;
positive integers. }while(num>0);
printf("Sum of all positive inputted integers is %d", sum);
return 0;
}
Sample Problems: Implement using do while Version2
#include<stdio.h>

Problem 7 int main()


{
int num = 0, sum = 0;
Make a C program that do
{
will input integers. The sum +=num; // use sum here if you don't want to add negative
program terminates if a number
negative number is printf("Enter a number:");
scanf("%d",&num);
inputted. Output the } while(num>0);
sum of all inputted printf("Sum = %d", sum);
return 0;
positive integers. }
Sample Problems: Implement using do while
int main()
{
int num, sum=0; //declaration part
Problem 7 do
{ printf("Enter number:");
scanf("%d", &num);
Make a C program that if(num<0)
will input integers. The break; //break will cause to exit from the loop
else
program terminates if a {
negative number is sum+=num;
continue; //continue will continue to execute do while loop
inputted. Output the }
} while(num>0);
sum of all inputted printf("The sum of all positive integers is %d", sum);
positive integers. return 0;
}
Do While
Do-while loop is usually used when we do not know exactly how many times
we need to execute repeating block of code, but we know that we need to
execute it at least once.

do {
/* repeating block of code */
} while (*);

do-while is same as while loop with difference that the condition is checked
at every iteration end. Consequence is that repeating block of code in
do-while loop is always executed at least once.
Control Flow

while statement

- Like do-while, this will execute a block of


codes while the given condition is true.
- It is a pre-checked loop because it checks
the controlling condition first before the code
is executed.
Control Flow
Syntax:
while (loop repetition condition)
{
statement/s;
}

Example:
c=1;
while (c<=5)
{
printf(“Hello World\n”);
c++;
}
Sample Problems: Implement using while
#include<stdio.h>
#include<conio.h>
//Make a C program to input 10 integers and will output their sum
Problem 1
int main()
{
Make a C program that int num, ctr=1, sum=0; //declaration part
will input 10 numbers. while(ctr<=10)
{
Output the sum. printf("Enter number%d:", ctr);
scanf("%d", &num);
sum=sum+num; //can be written also as sum+-=sum;
ctr=ctr+1; //can be written aslo as ctr++;
}
printf("The sum is %d", sum);
return 0;
}
Sample Problems: Implement using while
int main()
{
int num, ctr=1, ctr_pos_odd=0, sum_pos_odd=0; //declaration part
Problem 2 float ave_pos_odd=0.0;
while(ctr<=10)
{ printf("Enter number%d:", ctr);
Make a C program scanf("%d", &num);
if(num>0 && num%2!=0)
to output the { sum_pos_odd+=num;
average of all }
ctr_pos_odd++;

positive odd ctr=ctr+1; //can be written aslo as ctr++;


}
integers. ave_pos_odd=(float) sum_pos_odd/ctr_pos_odd;
printf("The average of all positive add ineteger is %0.2f", ave_pos_odd);
return 0;
}
Sample Problems: Implement using while
#include<stdio.h>
#include<conio.h>
//Make a C program to input an integer, output all the factors of the //number
Problem 3 excluding itself
Make a C program to int main()
{
input an integer. Output int num, ctr=1; //declaration part
all the factors of the printf("Enter number:");
scanf("%d", &num);
number excluding itself. printf("Factors are: ");
Sample output: while(ctr<num)
{
Enter an integer: 6 if(num%ctr==0) //check if num is divisible by current value of ctr
printf("%d ", ctr);
Factors are: 1 2 3 ctr=ctr+1; //can be written aslo as ctr++;
}
return 0;
}
Sample Problems: Implement using while
int main()
{
int num, sum=0; //declaration part
Problem 4 printf("Enter a temporary number:"); //temporary number
scanf("%d", &num);
while(num>0)
Make a C program that {
will input integers. The printf("Enter number:");
scanf("%d", &num);
program terminates if a if(num>0)
sum+=num;
negative number is else
inputted. Output the break; //break will cause to exit from the loop
}
sum of all inputted printf("The sum of all positive integers is %d", sum);
positive integers. return 0;
}
Sample Problems: Implement using while
int main()
Problem 5 {
int num,
return 0;
Make a C program }

to input a number.
Determine
whether the
number if PRIME
or COMPOSITE.
Sample Problems: Implement using while
int main()
Problem 5 {
int num,
Make a C program to input return 0;
}
2 numbers. Determine the
LCD of the given 2
numbers.
Sample 1
4 12 ans=4
Sample 2
24 12 ans=12
Sample
6 32 ans=2
Sample Problems: Implement using while
int main()
Problem 5 {
int num,
return 0;
Make a C program }

to input a fraction
in the form of a/b.
Output the lowest
term of the
fraction if it’s not
in lowest term.
Sample Problems: Implement using while
int main()
Problem 5 {
A Perfect number, a int num,
positive integer that is return 0;
}
equal to the sum of its
proper divisors. The
smallest perfect number
is 6, which is the sum of 1,
2, and 3. Other perfect
numbers are 28, 496, and
8,128. Make a C program
to input an inetger and
will determine if it’s
Perfect number or not.
Sample Problems: Implement using while
int main()
Problem 6 {
int num,
return 0;
Make a C program that
}
will input a number.
Output the factorial of a
number.

Ex.
Enter a number: 4
Factorial of 4 is 24
Enter a number: 5
Factorial of 5 is 120
Flowcharts of while and do while loops
While Loop
While loop is usually used when we do not know exactly how many times
we need to execute repeating block of code

while (*)
{
/* repeating block of code */
}

* Is a condition which is true or false. Ex. Value> 5


Condition is checked at every iteration start. If condition is true,
execution will continue, if it is false execution will break.
While and do while loops

Both while loops and do-while loops condition-


controlled, meaning that they continue to loop until
some condition is met.
Both while and do-while loops alternate between
performing actions and testing for the stopping
condition.
Control Flow
for statement
- a kind of loop command wherein the execution of the
statement does not depend on another instruction.
Syntax:
for (initialization expression; loop repetition condition; update expression)
{
statement/s;
}
Control Flow

Example

for (c=1; c<=5; c++)


{ printf(“Hello World\n”); }
Sample Problems: Implement using for loop
#include<stdio.h>
return 0;
}
Problem 0

Make a C program that


will print the first 50
even numbers.
Sample Problems: Implement using for loop
#include<stdio.h>
#include<conio.h>
//Make a C program to input 10 integers and will output their sum
Problem 1
int main()
{
Make a C program that int num, ctr, sum=0; //declaration part
will input 10 numbers. for(ctr=1; ctr<=10; ctr++)
{
Output the sum. printf("Enter number%d:", ctr);
scanf("%d", &num);
sum=sum+num; //can be written also as sum+-=sum;
}
printf("The sum is %d", sum);
return 0;
}
Sample Problems: Implement using for loop
int main()
{
int num, ctr, ctr_pos_odd=0, sum_pos_odd=0; //declaration part
Problem 2 float ave_pos_odd=0.0;
for(ctr=1; ctr<=10; ctr++)
{ printf("Enter number%d:", ctr);
Make a C program scanf("%d", &num);
if(num>0 && num%2!=0)
to output the { sum_pos_odd+=num;
ctr_pos_odd++;
average of all }
positive odd }
ave_pos_odd=(float) sum_pos_odd/ctr_pos_odd;
integers. printf("The average of all positive add ineteger is %0.2f", ave_pos_odd);
return 0;
}
Sample Problems: Implement using for loop
#include<stdio.h>
#include<conio.h>
//Make a C program to input an integer, output all the factors of the //number
Problem 3 excluding itself
Make a C program to int main()
{
input an integer. Output int num, ctr; //declaration part
all the factors of the printf("Enter number:");
scanf("%d", &num);
number excluding itself. printf("Factors are: ");
Sample output: for(ctr=1; ctr<num; ctr++)
{
Enter an integer: 6 if(num%ctr==0) //check if num is divisible by current value of ctr
printf("%d ", ctr);
Factors are: 1 2 3 }
return 0;
}
Sample Problems: Implement using for loop
int main()
{
Problem 4 }

Make a C program that


will input integers. The
program terminates if a
negative number is
inputted. Output the
sum of all inputted
positive integers.
Sample Problems: Implement using for loop
int main()
Problem 5 {
}
1. A Perfect number, is a
positive integer that is
equal to the sum of its
proper divisors. The
smallest perfect number
is 6, which is the sum of
1, 2, and 3. Make a C
program that will
determine if the number
is perfect or not.
Sample Problems: Implement using for loop
int main()
{
}
Problem 6
Make a C Program
to input 2 numbers.
Output their
product without
using the symbol *.
Sample Problems: Implement using for loop
int main()
Problem 7 {
}
Make a C Program to input
base and exponent. It will
compute base raise to
exponent. Also your program
will compute even with
negative exponent.
Ex1. Ex2.
base=2 base=3
exponent=4 exponent=-2
answer=16 answer=0.11
Sample Problems: Implement using for loop
int main()
Problem 7 {
}
Make a C Program to input
“N” number of integers.
Output the sum.
Sample Problems: Implement using for loop
int main()
Problem 8 {
}
Make a C Program
compute the sum of the
fraction series 1/1 + 1/2 +
1/3 + 1/4 + 1/n, where n is
the terminal value.
Implement using
a] do while
b] while
c] for loop
Sample Problems: Implement using for loop
SEAT WORK int main()
{
Make a C Program to input N integers. }
Output the highest and the lowest
integers.
Sample 1:
Enter N:5
5 2 9 12 7
High=12 Low=2
Sample 2:
Enter N:10
5 9 12 7 56 23 99 6 11 1
High=99 Low=1
Flowchart of for loop
Loop types (reminder)
Indefinite Loop:

 You do not know ahead of time how many times your loop will execute.
 For example, you do not know how many books a person might order.
Definite Loop:

 You know exactly how many times you want the loop to execute.
 not at compile time necessarily
Infinite Loop
You can still end up with an infinite loop when
using for loops

for (counter = 0; counter <= 10; counter--)


Types of Loop

Additional information on the


different types of Loops
Basic For Loop Syntax
For loops are usually used when we know exactly how
many times we need to execute repeating block of
code. It is also good for creating definite loops.
int counter;
1. Priming: Set 2. Test Condition: 3. Update: Update the
the start value. Set the stop value. value.

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


System.out.println (counter); Note that each section is
separated by a semicolon.
For Loop Flowchart
1. Priming
Set counter=1

2. Test TRUE 3a. print counter


counter
3b. Update counter++;
<= 10

FALSE
For Loop Variations
 The limit can be a variable:
for ( i = 1; i <= limit; i++)
 This counts from 1 to limit
 Update may be negative:
for (i = 100; i >= 1; i--)
 This counts from 100 to 1.
 Update may be greater than 1:
for (i = 100; i >= 5; i -= 5)
 This counts from 100 to 5 in steps of 5
When to Use Which Loop ?

If you know (or can calculate) how many iterations you need,
then use for loop.
Otherwise, if it is important that the loop complete at least once
before checking for the stopping condition, or if it is not
possible or meaningful to check the stopping condition before
the loop has executed at least once, then use a do-while loop.
Otherwise use a while loop.
Example

1. Make a flowchart that will input 10 integers. Output


the sum of the inputted integers.
2. Make a C program that will input 20 scores of
students. Output the average of the scores.
3. Make a C program to input 20 integers. Output
the average of all positive odd integers.
Example

1. Make a flowchart that will input 10 integers. Output


the sum of the inputted integers.
2. Make a C program that will input 20 scores of
students. Output the average of the scores.
3. Make a C program to input 20 integers. Output
the average of all positive odd integers.
Additional Problems
Make a C program to input an integer. Output the factorial of the
inputted integer. Use while or do while

A perfect number is a positive integer that is the sum of its factors


excluding the number itself is equal to the positive integer . The first
perfect number is 6, because 1, 2, and 3 are its factors, and
1 + 2 + 3 = 6 Make a C program that will prompts the user to enter a
number and determine if it’s a perfect number or not .
Sample Problems: Implement using any loop type
#include<stdio.h>
Problem #include<conio.h>
A perfect number is a positive //Make a C program to input an integer, determine if it’s a perfect number or not
integer that is the sum of its int main()
factors excluding the number {
int num, sum=0, ctr; //declaration part
itself is equal to the positive printf("Enter number:");
integer . The first perfect scanf("%d", &num);
number is 6, because 1, 2, for(ctr=1; ctr<num; ctr++)
{
and 3 are its factors, and
if(num%ctr==0) //check if num is divisible by current value of ctr
1 + 2 + 3 = 6 Make a C sum+=ctr;
program that will prompts the }
user to enter a number and if(sum==num)
pritnf(“%d is a PERFECT number!”, num);
determine if it’s a perfect else
number or not . printf(“%d is NOT A PERFECT number!”, num);
return 0;
}
Additional Problems
1. Make a C program to input positive integer. Compute for the factorial of the
inputted integer.
Example:
Enter a number: 4 Enter a number: 5
Factorial of 4 is 24 Factorial of 5 is 120

2. Make a C program to input 2 numbers. Output the product of the 2 numbers


withiut using the symbol *.
Example:
Enter 2 numbers:5 7 Enter 2 numbers:6 9
Product=35 Product=54
Solution to Problem 1
#include<stdio.h>
//Solution 1A
int main()
{
int num, ctr=1, fact=1;
printf("Enter a number:");
scanf("%d", &num);
for(ctr=1; ctr<=num; ctr++)
{
fact*=ctr;
}
printf("Factorial of %d is %d", num, fact);
return 0;
}
Solution to Problem 1
#include<stdio.h>
//Solution 1B
int main()
{
int num, ctr=1, fact=1;
printf("Enter a number:");
scanf("%d", &num);
for(ctr=num; ctr=>1; ctr--) //take note of the changes
{
fact*=ctr;
}
printf("Factorial of %d is %d", num, fact);
return 0;
}
Solution to Problem 2
#include<stdio.h>
//Solution 2A
int main()
{
int num1, num2, ctr=1, prod=0;
printf("Enter 2 numbers:");
scanf("%d %d", &num1, &num2);
for(ctr=1; ctr<=num2; ctr++)
{
prod+=num1;
}
printf("Produc = %d", prod);
return 0;
}
Solution to Problem 2
#include<stdio.h>
//Solution 2B
int main()
{
int num1, num2, ctr=1, prod=0;
printf("Enter 2 numbers:");
scanf("%d %d", &num1, &num2);
for(ctr=1; ctr<=num1; ctr++)
{
prod+=num2;
}
printf("Produc = %d", prod);
return 0;
}
Additional Problems (Hands On Exam)
1. Make a C program to input positive integer. Determine if the number is PRIME or
COMPOSITE.
Example:
Enter a number: 21
21 is COMPOSITE
Enter a number: 71
71 is PRIME

2. Make a C program to input 10 numbers. Output the lowest number.


Example
Enter 10 number: 23 5 7 90 45 32 87 21 9 88
Lowest = 5
Additional Problems (Hands On Exam)
1. Make a C program to input positive integer. Determine if the number is PRIME or
COMPOSITE.
Example:
Enter a number: 21
21 is COMPOSITE
Enter a number: 71
71 is PRIME

2. Make a C program to input 10 numbers. Output the lowest number.


Example
Enter 10 number: 23 5 7 90 45 32 87 21 9 88
Lowest = 5
Solution to Problem 1
#include<stdio.h>
#include<conio.h>
int main()
{
int num, ctr=1, cnt_factor=0;
printf("Enter a number:");
scanf("%d", &num);
for(ctr=1; ctr<=num; ctr++)
{
if(num%ctr==0)
cnt_factor++; //count the number of factors
}
if(cnt_factor<=2)
printf("%d is PRIME!", num);
else
printf("%d is COMPOSITE!", num);
return 0;
}
Solution to Problem 2
#include<stdio.h>
#include<conio.h>

int main()
{int main()
{
int num, ctr=1, low=1000;
for(ctr=1; ctr<=10; ctr++)
{
printf("Enter a number%d:", ctr);
scanf("%d", &num);
if(num<=low) //searching for low
low=num;
}
printf("LOW = %d", low);
return 0;
}
Additional Problem
1. Make a C program to compute the number (b) as base raise to exponent (e). Your
program must work to both positive and negative exponents, and also consider
that a number raise to 0 is 1.
Example:
Enter base: 2 Enter base: 4
Enter exponent: 3 Enter exponent:
2 raise to 3 is 8.000 4 raise to 4 is 256.000

Enter base: 2
Enter exponent: -3
2 raise to -3 is 0.125
Solution
#include<stdio.h>
//this program will compute b raise to e and works with +e and -e
int main() else //- exponent
{ if(expo<0) {
int base, expo, ctr; expo*=-1;
float value=1; for(ctr=1; ctr<=expo; ctr++)
printf("Enter base:"); {
scanf("%d", &base); value*=base;
printf("Enter exponent:"); }
scanf("%d", &expo); value=(float) 1/value;
if(expo>0) //if + exponent }
{ else //exponent is 0
for(ctr=1; ctr<=expo; ctr++) value-1;
{ printf(“%d raise to %d is %0.3f”, base,
expo, value);
value*=base; return 0;
} } //end of program
}
Additional Problems

Make a C program to input 5 names of


student. Each student has 3 exam
scores. Determine the average exam
score of each student. Output the
names with their corresponding average
score.
Additional Problems

Make a C program to print all the PRIME


numbers from 2 to 1000.
Additional Problems

Make a C program to print all the


PERFECT numbers from 1 to 100000.
Additional Problems
Make a C program to output the following figures shown
below:

a] * * * * b] * b’] * * * *
**** ** ***
**** * * * **
**** * * * * *
Solution to Figure a:
#include<stdio.h>
#include<conio.h>
//This program will print a box of asterisks
int main()
{ int row, col, max_col, max_row;
printf("Enter maximum rows:");
scanf("%d", &max_row);
max_col=max_row; //since figure is square
for(row=1; row<=max_row; row++) //this is for outer loop: row
{
for(col=1; col<=max_col; col++) //this is for inner loop: column
{
printf("*");
}
printf("\n"); //this will position the cursor to the next row
}
return 0;
}
Solution to Figure b:
#include<stdio.h>
#include<conio.h>
//This program will print a box of asterisks
int main()
{ int row, col, max_col, max_row;
printf("Enter maximum rows:");
scanf("%d", &max_row);
max_col=max_row; //since figure is square
for(row=1; row<=max_row; row++) //this is for outer loop: row
{
for(col=1; col<=row; col++) //this is for inner loop: column
{
printf("*");
}
printf("\n"); //this will position the cursor to the next row
}
return 0;
}
Additional Problems
Make a C program to output the number figures shown
below:

c] 1 d] 1 2 3 4 5
12 1234
123 123
1234 12
12345 1
Solution to Figure c:
#include<stdio.h>
#include<conio.h>
//This program will print a number figure
int main()
{ int row, col, max_col, max_row;
printf("Enter maximum rows:");
scanf("%d", &max_row);
max_col=max_row; //since figure is square
for(row=1; row<=max_row; row++) //this is for outer loop: row
{
for(col=1; col<=row; col++) //this is for inner loop: column
{
printf(“%d“, col);
}
printf("\n"); //this will position the cursor to the next row
}
return 0;
}
Solution to Figure d:
#include<stdio.h>
#include<conio.h>
//This program will print a number figure
int main()
{ int row, col, max_col, max_row;
printf("Enter maximum rows:");
scanf("%d", &max_row);
max_col=max_row; //since figure is square
for(row=max_row; row>=1; row--) //this is for outer loop: row
{
for(col=1; col<=row; col++) //this is for inner loop: column
{
printf(“%d“, col);
}
printf("\n"); //this will position the cursor to the next row
}
return 0;
}
Make a C program to output the number figures
shown below:

e] 1 f] 1
22 23
333 456
4444 7 8 9 10
55555 11 12 13 14 15
Solution to Figure e:
#include<stdio.h>
#include<conio.h>
//This program will print a a number figure
int main()
{ int row, col, max_col, max_row;
printf("Enter maximum rows:");
scanf("%d", &max_row);
max_col=max_row; //since figure is square
for(row=1; row<=max_row; row++) //this is for outer loop: row
{
for(col=1; col<=row; col++) //this is for inner loop: column
{
printf(“%d“, row);
}
printf("\n"); //this will position the cursor to the next row
}
return 0;
}
Solution to Figure f:
#include<stdio.h>
#include<conio.h>
//This program will print a number figure
int main()
{ int row, col, tmp=1, max_col, max_row;
printf("Enter maximum rows:");
scanf("%d", &max_row);
max_col=max_row; //since figure is square
for(row=1; row<=max_row; row++) //this is for outer loop: row
{
for(col=1; col<=row; col++) //this is for inner loop: column
{
printf(“%d“, tmp);
tmp++;
}
printf("\n"); //this will position the cursor to the next row
}
return 0;
}
Loop within a loop (Nested loops)
C programming language allows to use one loop inside another loop. Following
section shows few examples to illustrate the concept.

The syntax for a nested for loop statement in C is as follows:


for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s);
}
Loop within a loop (Nested loops)
The syntax for a nested while loop statement in C programming
language is as follows:
while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}
Loop within a loop (Nested loops)
The syntax for a nested do...while loop statement in C programming language
is as follows:
do
{
statement(s);
do
{
statement(s);
}while( condition );
}while( condition );
Going back to the First Problem
Make a C program to input 10 number of
students. Each student has 3 exam scores. Output
the names of the students with their
corresponding average scores.
Solution to Previous Problem
#include<stdio.h>

int main() //continuation

int ctr_stud, score, ctr_score, sum_score; stud_ave=(float) sum_score/3;


float stud_ave=0.0; printf("%s has average score of %0.2f", stud_name, stud_ave);
char stud_name[10][20] sum_score=0; // reset the score for the next student
for(ctr_stud=1; ctr_stud<=5; ctr_stud++) } //pair for for loop
{
fflush(stdin); return 0;
printf("\nEnter student%d:", ctr_stud); // END of program
gets(stud_name);
fflush(stdin);
for(ctr_score=1; ctr_score<=3; ctr_score++)
{
printf("Enter score%d:", ctr_score);
scanf("%d", &score);
sum_score+=score;
}
Additional Problems
Make a C program to input “N” number of
students. Each student has 3 exam scores. Output
the names of the students with their
corresponding average scores.
Additional Problems
Make a C program that will output all the prime
numbers from 2 to 1000.
Additional Problems
Make a C that will output all the PERFECT
numbers from 1 to 100000.
Loop within a loop (Nested loops)

A final note on loop nesting is that you can put


any type of loop inside of any other type of loop.
For example, a for loop can be inside a while
loop or vice versa.
Loop within a loop (Nested loops)
Some programmers like to use successive integers i, j, k, l, etc. for use in nested for
loops. This can be appropriate if the mathematics being implemented uses
multiple i j k subscripts.
Other times it can be less confusing to use alternative variables that are more meaningful to the
problem at hand, such as the r and c variables used above to keep track of rows and columns.
The limits as to how deeply loops may be nested is implementation dependent, but
is usually too high to be of any concern, except in cases of extremely complex or
extremely poorly written programs.
Additional Examples
Make a C program to input N number of integers.
Output the average of all positive odd integers.

Modify your program so that every time you run, it


will prompt the user to continue or not. If you press
Y it will run again, otherwise if you press any key it
terminates.
Additional Examples
1. Make a C program to input 10 names of student.
Each student has 5 exam scores. Determine the
average exam score of each student. Output the
highest average exam score.

2. Make a C program to determine the Least


Common Denominator of the 2 inputted numbers.
Additional Examples
3. Make a C program to input 15 exam scores. Output the
average exam score and also the exam scores that are greater
than the average exam score.

4. Make a C program to input 10 integers. Output the 4th, 7th


and 9th inputted integers only.
Computer Programming 1

THE END
PART A

You might also like