COMP
COMP
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 2 - Stores the data/instructions in its memory and uses them as required.
Advantages of Computers
Following are certain advantages of computers.
High Speed
Computer is a very fast device.
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.
Computers perform all jobs with 100% accuracy provided that the input is correct.
Storage Capability
Memory is a very important characteristic of computers.
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 perform repeated tasks with the same speed and accuracy.
Versatility
A computer is a very versatile machine.
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.
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
Business
A computer has high speed of calculation,
diligence, accuracy, reliability, or versatility which
has made it an integrated part in all business
organizations.
Payroll calculations
Budgeting
Sales analysis
Financial forecasting
Managing employee database
Maintenance of stocks, etc.
Banking
Today, banking is almost totally dependent on
computers.
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.
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).
Marketing
9
In marketing, uses of the computer are following:
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.
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.
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
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.
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.
14
Non-portable
Consumed a lot of electricity
ENIAC
EDVAC
UNIVAC
IBM-701
IBM-650
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
IBM 1620
IBM 7094
CDC 1604
CDC 3600
UNIVAC 1108
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
IBM-360 series
Honeywell-6000 series
PDP (Personal Data Processor)
IBM-370/168
TDC-316
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.
DEC 10
18
STAR 1000
PDP 11
CRAY-1(Super Computer)
CRAY-X-MP(Super Computer)
AI includes:
Robotics
Neural Networks
Game Playing
Development of expert systems to make decisions in real-life situations
Natural language understanding and generation
Desktop
Laptop
NoteBook
UltraBook
ChromeBook
20
4. Computer Fundamentals ─ Types
Sr.
Type Specifications
No.
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.
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.
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.
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.
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/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
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.
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.
C is a concise language
it has only about 32
keywords
it encourages concise code.
General Description of C
C is weakly typed
allowing quite a bit of data
conversion and providing
minimal run time checking.
C Language Elements
#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.
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; }
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
#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
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
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.
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
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
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:
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
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
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/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
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
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
2 Types:
- used in boolean expressions and consists of logical “and", “or" and “not".
0-> false and 1-> true or nonzero digit
! !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.
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.
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
Syntax:
if (condition) Condition T Statement
statementT;
else F
statementF; Statement
Good Programming Practice
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.
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.
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 (>)
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.
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
Enter a number:23
23 is ODD
Control Flow
Switch Statement
Break
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
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.
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/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
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:
3 Types:
1. do-while statement
2. while statement
3. for statement
Control Flow
do-while statement
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>
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++;
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>
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
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++;
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 */
}
Example
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
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
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
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 END
PART A