introduction to c++ (using microsoft visual c++) · the first lab of c++ will describe how to use...
TRANSCRIPT
1
1 Introduction
The first lab of C++ will describe how to use the Integrated Development
Environment (IDE) of the Microsoft Visual C++ 2010 (MSVC). The lab begins with a
brief explanation of the IDE where it covers from the beginning of constructing a C++
program until the program’s output. Then student will be introduced to the structure of a
simple C++ program. Before writing the first C++ program using MSVC, basic
command of output will be described.
By the end of this section, the students should be able to:
Understand the basics of C++ programs and its
development environment.
Develop a simple C++ program of the Console
Application type using the Microsoft Visual C++.
Introduction to C++ (using Microsoft Visual C++)
2
1.1 Theoretical Background
1.1.1 A Typical C++ Environment
A C++ system generally consists of three parts which are; a program development
environment, the language, and the C++ Standard Library. Let's consider the steps in
creating and executing a C++ program using a C++ development environment
(illustrated in Figure. 1.1). Every C++ program typically goes through these five steps:
edit, compile, link, load and execute.
1. Text Editor
Program is created in
the editor and stored
on a disk
2. Compiler
2.1 Preprocessor
Preprocessor program
process the code
2.2 Translator
Converting the
program to machine
language (object code)
3. Linker
Links the object code
with C++ libraries to
form an executable
program4. Loader
On OS command (run),
Loader will locate the
executable program and
reads it into memory to
begins execution.
Figure 1.1 A typical C++ program development environment.
A program is also called source code. A preprocessor is another
program that removes all comments and modifies source code,
according to the commands called preprocessor directives (statements
begin with #) found in the source code .
3
1.1.2 A simple C++ program
Figure 1.2 shows the typical structure of a simple C++ program, with Program 1 as an
example. Meanwhile, Table 1.1 describes the structure of Program 1.
Comments
Preprocessor
Directive
Global declaration
Namespace
User-defined function
(see Lab 4)
Main function
1
6
5
4
3
2
/*Program 1: This program demonstrates
a simple C++ program*/
#include <iostream>
void fun();
using namespace std;
void fun()
{
cout<<”C++ is fun!”;
cout<<endl;
}
int main()
{
cout<<”Welcome to C++ Lab\n”;
fun();
return 0;
}
1
6
5
4
3
2
Figure 1.2 Typical structure of a C++ program.
Table 1.1 Descriptions of Program 1’s structure
No. Description
1 Comments: Internal programming documentation. Comments will be ignored
by compiler, and comments do not affect the way the program runs.
Programmers use them to include short explanations or observations
concerning the code or program.
2 Preprocessor Directive: The directive #include <iostream>, instructs
the preprocessor to include a section of standard C++ code, from a header file
known as iostream, that allows this program to perform standard input and
output operations, such as writing the output of this program to the screen.
3 Namespace: Namespace is a collection of classess, objects, functions,
variables, constant, and types that are enclosed in the C++ libraries. When you
use using namespace std; you are instructing C++ compiler to use the
4
standard C++ library.
4 Global declaration: Declarations that are visible to all parts of the program.
5 Main function: The starting point of a C++ program’s execution. Contains a
group of statements (program instructions). Every C++ program must have this
function.
6 User-defined functions: A group of statements that were defined by the
programmer.
1.1.3 Basic Command of Output
Below are some basic commands to understand your first program.
cout<< : an output object that sends data to the standard output display
device, e.g. monitor.
Escape sequence: Consists of two characters. First is the backslash character (\),
next the character that determines the interpretation of the escape sequence.
Table 1.2 below lists some commonly used escape sequences.
Table 1.2 Commonly used escape sequence
Escape
Sequence Name Description
\a Audible alert Bell sound
\t Horizontal Tab Takes the cursor to the next tab stop
\n or endl New line Takes the cursor to the beginning of the next
line
\" Double Quote Displays a quotation mark (")
\' Apostrophe Displays an apostrophe (')
All C++ statements except preprocessor directive end with a
semicolon (;).
C++ functions must have an opening and matching closing
bracket. ( {…<statement>…} )
5
\? Question mark Displays a question mark
\\ Backslash Displays a backslash (\)
1.2 Step by step Examples
1.2.1 Your First Program
1. Start the MS Visual Studio 2010 software from the task bar, that has the main
window similar to the display below:
6
2. The first step in writing a Visual C++ program is to create a project for it. In the
menu bar, click File -> New -> Project...
3. In the New Project dialog box shown below, select by clicking Visual C++ in the
Installed Template pane and Win32 Console Application in the middle pane.
4. In the Name text box, give the project a name, e.g. Exercise1
5. In the Location text box (at the bottom of the dialog box), specify the path of the
project (e.g. C:\LAB1), or select the location or folder in which you’d like to store
the project files by clicking Browse…
6. Click OK. Note that there is no need to enter a name in the Solution name text box;
the system fills the project name in it by default.
7. In the Win32 Application Wizard - Exercise1 dialog box, click Next >
7
8. In the Additional Options section, click the Empty Project check box. Then click
Finish.
9. To create a new C++ program file, right click the Source Files Folder on the
Solution Explorer. In the popup menu, click Add then New Item or in the menu
bar, click Project -> Add -> New Item...
8
10. In the Installed Templates list of the Add New Item dialog box, make sure Visual
C++ is selected.
11. In the middle pane, click C++ File (.cpp).
12. In the Name text box, give the C++ program file a name, e.g: Exercise. Then click
Add.
13. You have just created an empty C++ source file (Exercise.cpp) and added it to the
project (Exercise1). The main window will display the text editor, ready for editing
9
this new C++ file (Exercise.cpp). Fill the contents of file Exercise with the
following C++ program:
/*Program 1: This program demonstrate a simple C++
program*/
#include <iostream>
using namespace std;
int main()
{
cout << "Welcome to Lab 1!!!\n";
return 0;
}
14. To compile and link the program, on the main menu, click Build -> Build
Exercise1; or press Ctrl+F7.
15. If there is no error in your project, the message :
====== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped =====
is displayed in the Output window as shown below.
10
16. To load, execute and see the output, on the main menu, click Debug-> Start
without Debugging; or press Ctrl+F5.
11
17. Displayed in a DOS window (C:\Windows\system32\cmd.exe) is the program’s
output:
18. After viewing the result, press any key on the keyboard to close the program’s
output and return to MSVC.
Syntax error: Syntax is the set of rules for forming valid
instructions. Syntax error violates the syntax of a language.
Warning message: Message from a compiler advises the
programmer that a statement is technically acceptable but might
have a potential error.
12
1.3 Exercises
1. Write a program that can print as the following:
University : Universiti Teknikal Malaysia, Melaka
Faculty : FKE
Programme : BENC
My name is Muhammad Bin Abdul Rahman. I am from Johor.
2. Write programs that can give the following output:
a)
b)
The background / foreground colour for the output screen, its font,
size etc can be set in the output windows property.
13
1.4 Self-Review Questions
1. Give appropriate programming terms for the following:
a) A program written in high-level or assembly language.
b) A mistake that is a direct violation of the syntax rules.
c) A program compiles and runs, but gives an incorrect output.
d) It links object code with the C++ library to form executable code.
e) The language, made up of binary coded instructions, that is used directly by the
computer.
f) A program that translates a program written in a high-level language into
machine language.
g) A machine language version of source code.
h) An interactive program used to create and modify programs or data.
i) Statement that begins with #.
j) Punctuation that signifies the end of a C++ statement.
Answer:
a)
b)
c)
d)
e)
f)
g)
h)
i)
j)
14
2. State whether the following statements is TRUE or FALSE.
a) The purpose of a header file such as iostream is to store a
program’s source code.
b) The C++ standard function to read data from keyboard is cin.
c) In general, C++ statements are case-sensitive.
d) One and only one function may be named main.
e) Comments are used by the preprocessor to help format the
program.
3. a) List the sequence of steps associated with implementing a program.
b) State the difference between:
i. syntax error and logic error
ii. logic error and run-time error
iii. testing and desk checking
c) Define the term ‘test data’.
Answer:
15
//Program 1: This program that will print lines
#include <iostream>
using namespace std;
int main()
{
cout << "ONE\tTWO"<<endl;
cout << "THREE\n\n\FOUR\n\n\n";
cout << "\tFIVE\tSIX";
cout << endl<<endl<<"SEVEN EIGHT NINE\n\n";
return 0;
}
Output:
//Program 2: This program will print asterisk
#include <iostream>
using namespace std;
int main()
{
cout << "o\t*o\n";
cout << "***o\n*******o";
cout << "\n*****";
cout << "*******o\n*******************o\n";
return 0;
}
Output:
4. Give the output of the following program:
5. Give the output of the following program:
16
2 Introduction
Programming is a problem-solving activity. Problem solving method varies according to
the subject area. For example, engineering problems are solved through scientific
method, while business problems are solved using business system approach. For
programming problem, it is solved using software development method. A basic
software development method consists of four common steps as follows:
a) Step 1: Analysis
b) Step 2: Design the algorithm
c) Step 3: Code
d) Step 4: Test
In Lab 2, you will learn the activities that need to be done in Step 1 and Step 2.
By the end of this section, the students should be able to:
Understand the basic techniques of problem solving.
Develop structure chart, flowchart and pseudocode.
Use Microsoft Visio 2003 for creating structure chart,
flowchart and pseudocode.
Introduction to Problem Solving
17
2.1 Theoretical Background
2.1.1 Step 1: Analysis
In this step, you have to highlight the problem statement and eliminate unimportant
aspects in the problem. There are two main activities in this step:
a) Identify what are the input, processes and output (IPO) of the problem.
b) Draw a structure chart (if needed). The structure chart is developed if you want
to use top-down design, in which you divide the problem into several sub
problems.
2.1.2 Step 2: Design the Algorithm
This step is to define the detail actions/instructions to solve the problem or subproblem,
based on the IPOs outlined in Step 1. The actions consists of using the input, and
executing a series of process in a specific order to produce the desired output. This
group of actions is referred as algorithm.
Algorithm is a procedure for solving a problem or subproblem in terms of the actions to
be executed, and the order in which these actions are to be executed. Carefully prepared
algorithm may be converted easily to program. Algorithm can be written in pseudocode
or flowchart:
a) Pseudocode
Pseudocode is an informal language that helps programmers develop
algorithms for programs or subroutines.
It is not a programming language, and it is similar to everyday language.
Its purpose is to describe in precise words the algorithm details.
Pseudocode defines the steps of action to accomplish the tasks in sufficient
details.
18
b) Flowchart
A diagram that helps programmers develop algorithms for programs and
subroutines.
Table 2.1 shows the common flowchart’s symbols.
Table 2.13 Common flowchart’s symbols
Symbol Name Description
Terminal/Terminator The beginning or end of a
program.
Process Computation or data
manipulation.
Data An input or output
operation.
Decision A program branch point.
On-page reference/
Connector
An entry to, or an exit
from, another part of the
flow chart.
Predefined process Call for a function
(subroutine).
Flow lines Connecting the flowchart’s
symbols.
Each symbol indicates the type of operation to be performed.
Flowchart graphically illustrates the sequence in which the operations are to
be performed (executed). Therefore the algorithm flow of execution is better
understood with a flowchart.
19
Condition
Statement 1
Statement 2
TRUE
FALSE
Statement
CONDITION
TRUE
FALSE
There are three kinds of basic control structures, use in designing problem’s solution:
a) Sequence: is a series of statements that execute one after another.
b) Selection (branch): is used to execute different statements depending on certain
conditions. Eg: IF condition evaluates to true THEN executes statement1 ELSE
executes statement2.
c) Repetition (loop or iteration): is used to repeat statements while certain
conditions are met.
Statement 1 Statement 2 Statement 3
20
2.2 Step by step Examples
2.2.1 Drawing flowchart using Microsoft Visio
1. Start Visio 2003 : Click Start -> Program -> Microsoft Office > Microsoft Visio
2. Choose the drawing type: On the Category section (on the left), click on the
Flowchart folder, and select Basic Flowchart on template column.
21
3. A drawing canvas and basic flowchart’s shapes will be shown.
4. To create a new symbol, (e.g. process symbol), , click on the process item and drag it
on to the grid paper.
22
5. To save the drawing, click on File menu ->Save as -> click the Save button.
6. To add others drawing type. Click File ->New -> and select the drawing type you
want.
Other software that can be used to draw a flowchart is
Dia(https://wiki.gnome.org/Dia). Dia is an open source application,
and works cross platform.
23
2.3 Problem Solving (Step 1 and Step 2)
2.3.1 Example 1: Employee’s Salary (using top-down approach)
Given the employee’s working hour, a program will calculate and display the salary for
an employee. The pay rate for an hour is RM 6.50.
Step 1: Analysis
i. Identify input, process, and output.
a) Input: Employee’s working hour, HOUR
b) Process:
i. Accept HOUR.
ii. Calculate salary based on the pay rate per hour,
SALARY = HOUR x 6.5
iii. Display SALARY.
c) Output: SALARY
ii. Structure chart.
Employee’s salary
problem
Input the employee’s
working hourCalculate the salary Display the salary
Step 2: Design the Algorithm
i. Pseudocode of the main module of the Employee’s Salary Problem:
main()
1. Start
2. Call input()
3. Call calculateSalary()
4. Call display()
5. End
ii. Pseudocode of submodule to input the employee’s working hour:
input() 1. Start
24
2. Read the employee’s working hour, HOUR
3. Return
iii. Pseudocode of submodule to calculate the employee’s salary:
calculateSalary()
1. Start
2. SALARY = 6.5*HOUR
3. Return
iv. Pseudocode of submodule to display the employee’s salary:
display()
1. Start
2. Display SALARY
3. Return
v. Flowchart of the Employee’s Salary Problem:
START
input()
calculateSalary()
displaySalary()
END
input()
Read employee’s
working hour,
HOUR
RETURN
calculateSalary()
SALARY = HOUR*6.5
RETURN
displaySalary()
SALARY
RETURN
25
2.3.2 Example 2: Arithmetic Problem (not using top-down approach)
A program will add two numbers and print a message whether the sum is an even
number or an odd number. The program will repeat for five times.
Step 1: Analysis
i. Identify input, process, and output.
a) Input: Five sets of two numbers, NUM1 and NUM2.
b) Process:
i. Accept two numbers, NUM1 and NUM2
ii. Add the two numbers, SUM = NUM1+NUM2
iii. Check SUM whether it is odd or even number.
iv. Display the suitable message.
v. Repeat the process for five times.
c) Output: Message “sum is an even number” or “sum is an odd number”.
Step 2: Design the Algorithm
i. Pseudocode:
1. Start
2. Set COUNTER=0
3. While COUNTER < 5
4. Read two numbers: NUM1, NUM2
5. SUM = NUM1+ NUM2
6. If SUM is an even number
Print “EVEN NUMBER”
7. Else
Print “ODD NUMBER”
8. Add 1 to COUNTER
9. Endwhile
10. End
26
ii. Flowchart:
START
READ NUM1,
NUM2
SUM = NUM1 + NUM2
SUM IS EVEN
NUMBER?
PRINT “EVEN
NUMBER”
END
“ODD
NUMBER”
COUNTER = 0
COUNTER < 5?False
True
True
False
COUNTER = COUNTER + 1
27
2.4 Exercises
For each of the following problems, identify the problem inputs, processes, and problem
outputs. Then write pseudocode and create flowchart for each solution.
1. A program will change a temperature reading from Celsius to Fahrenheit. Prompt
the user to enter the temperature in degree Celsius and display the temperature in
Fahrenheit. (Fahrenheit = 32 + (9*Celsius/5))
2. Let a runner insert how many steps he has run in one minute, and the running
duration in minutes and seconds. Find how many miles he has run. Assume each of
his step length is 2.5 feet. (1 mile = 5280 feet)
3. Accept two numbers and find their sum and difference. If the sum is more than the
difference, display the sum otherwise display the difference.
4. This is a program to calculate and display the body mass index (BMI). The BMI is
to determine whether a person is overweight, underweight or has an optimal weight
for his/her height. A person’s BMI is calculated using the formula BMI = weight /
height2 . A sedentary person’s weight is considered to be optimal if his/her BMI is
between 18.5 and 25. If the BMI is less than 18.5, the person is considered to be
underweight. If the BMI value is greater than 25, the person is considered to be
overweight.To determine the BMI, let the organiser enters the total number of
people participating in this program. Then let each participant enters his/her weight
(in kg) and height (in meters); and as a result, the participant gets a message
indicating whether he/she has optimal weight, is underweight, or is overweight.
Repeat the process for all participants.
5. Insert a few integer numbers between -100 and 100 (insert the value 0 to stop).
Determine how many negative numbers and how many positive numbers have been
inserted, the smallest number and the biggest number, their total and average. Print
out what have been determined. (Consider to use the top-down approach in your
design).
28
2.5 Self-Review Questions
1. Answer the questions below:
a) The following are problem-solving stages. List the stages in their correct order.
i. Analyse the problem
ii. Suggest possible solutions
iii. Test and validate the algorithm
iv. Define the problem
v. Represent the algorithm of the solution
vi. Select the best solution
b) Which one of these two is more difficult to do and should not be taken lightly,
problem-solving or programming? Explain your answer.
c) What is an algorithm?
d) List four characteristics of a good algorithm.
e) What are the three main things to identify before creating an algorithm?
f) Is an algorithm the same as a program?
g) What is the difference between pseudocode and flowchart?
h) Which of the following are algorithms?
i. Directions on a box for preparing one bowl of oatmeal.
ii. List of nutrients in the oatmeal.
iii. List of health recommendations for a long life.
iv. Directions for filling out a registration form.
v. Rules for dividing one number by another.
i) Name three types of control structures that are commonly used to solve problem.
29
j) What is a top-down design approach?
k) Explain why a top-down design approach is sometimes used to solve problems.
l) A hotel wants to have a room booking system. When a guest arrives the
receptionist would be able to see which rooms are free and allocate one to the
guest. When the guest leaves, the room would be marked as free again. At any
time the receptionist would be able to use the room number to find the name and
home address of a guest, or could search the room system for a named guest.
Draw a top-down design diagram (structure chart) to show how the room
booking system could be developed.
2. Create a trace table to determine the output of the following pseudocode:
a) Step 1: start
Step 2: set x = 5
Step 3: set y = 10
Step 4: set z = 3
Step 5: set x = x + y
Step 6: set y = x + z
Step 7: set z = x + y + z
Step 8: display x, y, z
Step 9: stop
30
b) Step 1: start
Step 2: set a = 10
Step 3: set b = 12
Step 4: set c = 23
Step 5: set a = a + b + c
Step 6: set b = a - b
Step 7: set c = b - c
Step 8: if a>b then
set m = a
set n = b
set p = c
else
set m = c
set n = a
set p = b
endif
Step 9: display m,n,p
Step 10: stop
c) Step 1: start
Step 2: set a = 7
Step 3: set x = 1
Step 4: while a<>0
set x = x + a
set a = a − 1
endwhile
Step 5: write x
Step 6: end
31
d) Step 1: start
Step 2: set x = 5
Step 3: for i = 1 to 10
set x = x + 5
endfor
Step 4: write x
Step 5: end
e) Step 1: start
Step 2: read 2 integers; A, B
Step 3: do
print A
A = A - 1
while (A > B)
Step 4: print B
Step 5: stop
(Note: Assume that the user enters 5 and 3)
3. Create flowchart for the pseudocode in question 2 a)-e).
32
3 Introduction
C++ is a structured programming language, and considered as a high level language
because it allows the programmer to concentrate on the problem and not worry about
the machine that the program will be using. C++ is actually evolved from C over a
period of several years. C was designed by Dennis Ritchie in 1972. While the evolve
version of C is named C++ and largely the work of Bjarne Stroustrup. In 1997,
American National Standard Institute (ANSI) and the International Standard
Organization (ISO) jointly develop the standard for C++ which is being used until
today.
By the end of this section, the students should be able to:
Understand the fundamental data types, constant,
variables, as well as operators and its precedence.
Develop a simple C++ program.
Introduction to C++ Programming Language
33
3.1 Theoretical Background
3.1.1 Data Types
Data type is the classification of type of data, that identify a value.
Standard data types are fundamental data types, which include:
a) Integers (int/long/short) : whole number. E.g. 20 , 100, 35
b) Floating point (float/double) : real number with integral and fractional
part separated by decimal point. E.g. 3.14, 500.678, 100.00
c) Character (char) : individual character value which enclosed in a set of
single apostrophes. E.g. ‘D’, ‘r’, ‘4’
d) Boolean (bool) : Value either true (nonzero) or false (zero).
3.1.2 Identifiers
Used to name constants, variables, function names and labels. Identifiers are
formed by combining letters (both upper and lower case), digits and underscore.
Rules : First character of an identifier must be letters or underscore ( _ ), case-
sensitive, blank spaces and special symbols are not allowed.
Reserved word or keywords cannot be used to name an identifier.
Examples of valid identifiers are:
Nombor1 , V , _ARUS , Proses( ) , Rintangan_1 , nAME, INT
Examples of invalid identifiers are:
17th , COUNTER NUMBER , B*, int, return
Variable: Identifiers whose value may change during execution. Variables represent
memory location where values such as digits and characters can be stored.
34
3.1.3 Keyword/Reserved Word & Special Symbols
A word that has special meaning in C++. Used only for their intended purpose. All
reserved word appears in lowercase.
E.g: const, goto, continue, do, double, else, float, while,
int, switch
Special symbols in C++ : [ ] ( ) { } , ; : * #
3.1.4 Constant
Values that do not change during execution of program.
Two ways of constant declaration in a program: by using #define and reserved
word const
E.g:
#define PI 3.14
#define IC "A1112222"
const double PI = 3.14;
The naming of a constant should follow the rules of naming identifiers.
35
3.1.5 Operators
A. Unary Operators
B. Arithmetic Operators
Operation Symbol Syntax
Addition + x + y
Subtraction - x – y
Multiplication * x * y
Division / x / y
Modulus % x % y
Plus + + x
Minus - - x
C. Assignment Operators
Symbol Syntax Equal to
= x = 5 -
+= x+=2 x = x + 2
-= x -=3 x = x – 3
*= x*=7 x = x * 7
/= x/=5 x = x / 5
%= x%=4 x = x % 4
Predecrement/Preincrement
--r / ++r : decrease / increase r by 1 then use the new value of r for next execution
Postdecrement/Postincrement
r-- / r++ : the current value of r will be used first, and then only the r will be
decrease / increase by 1
36
D. Relational Operators
Operator Example True if Expression Value
= = x = = y x and y are equal x = = y False (0)
!= x != y x and y are not equal x != y True (1)
> x > y x is greater than y x > y False (0)
>= x >= y x is greater than or equal to
y
x >= y False (0)
< x < y x is less than y x < y True (1)
<= x <= y x is less than or equal to y x <= y True (1)
E. Logical Operators
Operator Name Example True if
&& Conjunction x && y x and y are both true
| | Disjunction x | | y x or y (or both) is true
! Negation ! x x is false
3.1.6 Operator Precedence Hierarchy
Operator category Operator
Parentheses ( )
Unary ++ -- ! -
Arithmetic * / %
Arithmetic binary + -
Relational < <= > >=
Relational (Equality Operators) = = !=
Logical AND &&
Logical OR | |
Assignment = += -= *= /= %=
37
3.2 Step by step Examples
3.2.1 Example 1: Arithmetic Operators
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/*Program 1: This program demonstrates C++ elements in
converting distances from miles to kilometers*/
#include <iostream>
using namespace std;
#define MILE_TO_KM 1.609
int main( )
{
double miles, km;
cout<<"Enter the distance in miles: " <<endl;
cin >> miles;
km = miles * MILE_TO_KM;
cout<<"\nThat equals " << km << " kilometers " <<endl ;
return 0;
}
Output:
Enter the distance in miles: 20
That equals 32.18 kilometers
Line Description
4 #include <iostream>
Preprocesor directive
6 #define MILE_TO_KM 1.609
MILE_TO_KM : constant declaration
8 int main( )
main : reserved word
10 double miles, km;
miles, km : variables
14 km = miles * MILE_TO_KM;
= : Assignment operator
* : Arithmetic operator
16 return 0;
return : reserved word
38
3.2.2 Example 2: Operator Precedence
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/*Program 2: This program demonstrate unary, arithmetic,
assignment operator, and its precedence*/
#include <iostream>
using namespace std;
int main( )
{
int a=5, b=6, c=7;
int x, y = 3;
x = --a * (3 + b) / 2 - c++ * b;
y %= 5; y += c;
cout << "Value of x is " << x << endl;
cout << "Value of y is " << y <<endl ;
cout << "Value of a is " << a << endl;
cout << "Value of b is " << b <<endl ;
cout << "Value of c is " << c << endl;
return 0;
}
Output:
Value of x is -24
Value of y is 11
Value of a is 4
Value of b is 6
Value of c is 8
Line Description
11 x = --a * (3 + b) / 2 – c++ * b;
Steps in evaluating the expression :
1. Parentheses : (3 + b) = 3 + 6 = 9
2. Pre-unary operator : --a = --5 = 4
3. Multiplication (from left to right): 4*9 = 36
4. Division (from left to right): 36/2 =18
5. Multiplication (from left to right): c*b=7*6=42
6. Subtraction: 18 – 42 = -24
7. Assign the result to x: x = -24
8. Post-unary operator: c++ = 7++ = 8
Values after expression:
a=4, b=6, c=8, x=-24, y=3
39
12 y %= 5
Steps in evaluating the expression :
1. y = y % 5
2. y = 3 % 5 = 3
y += c;
Steps in evaluating the expression :
1. y = y + 8
2. y = 3 + 8 = 11
Values after expression:
a=4, b=6, c=8, x=-24, y=11
3.2.3 Example 3: Relational and Logical Operators
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*Program 3 : This program demonstrate the relational and
logical operators*/
#include <iostream>
using namespace std;
void main()
{
int num1, num2;
cout << "Enter two integers to know "
<<"the relationship that they satisfy"<< endl;
cin >> num1 >> num2;
if (num1 == num2)
cout << num1 << " is equal to " << num2;
else if ((num1 != num2) && (num1 < num2))
cout << num1 << " is less than " << num2;
else if ((num1 != num2) && (num1 > num2))
cout << num1 << " is greater than " << num2;
}
Output:
Enter two integers to know relationship that they satisfy:
22 12
22 is greater than 12
40
Line Description
10
11
cout << "Enter two integers to know "
<<"the relationship that they satisfy"<< endl;
Program prompt user to enter integers.
12 cin >> num1 >> num2;
Read 2 integers, put in num1 and num2.
14 if (num1 == num2)
Compares the values of num1 and num2 to test for equality.
15 cout << num1 << " is equal to " << num2;
Display a line of text indicating that the numbers are equal.
16 else if ((num1 != num2) && (num1 < num2))
Compares the values of num1 and num2 to test for equality and to test
whether num1 is smaller than num2
17 cout << num1 << " is less than " << num2;
Display a line of text indicating that the num1 is less than num2
18 else if ((num1 != num2) && (num1 > num2))
Compares the values of num1 and num2 to test for equality and to test
whether num1 is larger than num2
19 cout << num1 << " is greater than " << num2;
Display a line of text indicating that the num1 is larger than num2
41
3.3 Exercises
1. Code the variables definition and the process for each of the following:
a) A floating point named price initialized to 9.90.
b) An integer named quantity.
c) A constant integer named DISC initialized to 10.
d) A floating point name totalprice.
e) Get the quantity purchased from the user and then, calculate the totalprice
using the following formula:
totalprice = (price*quantity) * (100-DISC)/100.00;
2. Write a program that prompts the user to enter the total time in seconds and displays
the hours, minutes and seconds for the total time. Declare two constant integers
named SCND_TO_HOUR initialized to 3600 and SCND_TO_MINUTE initialized to 60.
For example, 5000 seconds are equal to 1 hour, 23 minutes and 20 seconds. Here is
a sample run:
3. Write a program that reads in loan amount, annual interest rate and number of years
for the loan and display monthly payment the customer should pay for the loan.
Here is a sample run:
Input the total time in seconds : 5000
5000 seconds are equal to 1 hours, 23 minutes and 20 seconds.
Input loan amount (RM): 30000
Input annual interest rate (%) : 4.2
Input number of years : 10
Monthly payment for this loan is (RM): 355
42
4. In physics, an object that is in motion is said to have kinetic energy. The following
formula can be used to determine a moving object’s kinetic energy:
KE = (1/2 mv2)
Where
KE =the kinetic energy
m = the object’s mass in kilograms
v = the object’s velocity in meters per second.
Write a program to calculate the amount of kinetic energy that the object has when
given the object’s mass (in kilograms) and velocity (in meters per second). Here is a
sample run:
Input the object’s mass (kg):10.0
Input the object’s velocity (m/s): 5
The kinetic energy (Joules): 125
43
3.4 Self-Review Questions
1. Indicate whether the following identifiers VALID or INVALID. Explain if invalid.
Identifier Valid / Invalid ? Why Invalid ?
employee name
_int_
tot&Salary
$RM
number1
3rdnumber
else
EmpPosition
number_2
double
2. The _____________________ logical operator is true only when at least one of the
operands is TRUE.
3. If x=false, y=true, and z= true, what is the value of each of the following
expressions?
a) x && y || z
b) x || y && z
c) (x && y) || z
d) (x || y) && z
e) (x && z) || y
4. Show the value of x after each statement is performed:
a) x = 6 + 4 * 8 /(2 – 1);
b) x = 6 % (4 + 2) * 4 – 2 / 2;
44
c) x = ( 3 * 7 * ( 3 + ( 2 * 12 / (4) ) ) );
d) x = 6 * (3 + 18) / 2 – 5 * 4;
5. Find any errors in the following program:
integer main()
{
int 1num, num 2, num3;
character id;
1num + num 2 = num3;
cout << id << num3 << \n;
return;
}
6. If originally x=6, y=3, and z=2, what is the value of each of the following
expression?
a) x - z * 6 / y
b) y++ * (x + y) % z + y
c) ++y + z-- + x++
d) x++ – 3 * ++z + 2
e) ++x – 2 * (5 - ++z) + y