Chap2 (Basic C++ Prog)
Chap2 (Basic C++ Prog)
____________________________________________________________________________________
#include<iostream.h>
int main()
{
cout<<” Hello World”;
return 0;
}
Comments.
- The second, third and fourth lines are comments.
- It is identified by the double slashes // for single line comment and /*to start the
comment and */ to close the comment for comments having more than one lines
(block of comment).
- To provide explanations for human readers.
- The braces {} determine the beginning and end of the function body.
- The statements inside the braces determine what the function does.
- Each statement inside the function must end with a semicolon (;) .
String Literals.
- The statements “Hello World” is called string literals.
- It consist sequence of characters delimited by quotation marks.
2.2.1 Identifiers.
- An identifier is a string of alphanumeric characters that begins with an alphabet.
- Used to name things.
- To give name to the variables, constant, functions, classes and etc.
- Formed by:
combining letters, digits and underscore
first character must be a letter or an underscore
blank/whitespace is not permitted.
Symbols/special characters are also not permitted.
Maximum to 31 characters.
Named the identifier that reflect the data items.
2.2.2 Keywords
- words that are reserved by the language of C++ for special purpose.
- Also called reserved words.
- Have standard and predefined meanings.
- Cannot be redefined for use as variable or any other purpose.
- Ex: main, cout, cin, class, if, then…..etc.
2.2.3 Variables
- Identifiers whose value may change during the execution of a program.
- Refer to a location in computer’s memory to store data.
- Variable naming must follow the rules to form an identifier mentioned above.
- Must be declared first before can be used in a program.
- Declaration statement:
datatype variablename; or
datatype variable1,variable2,…variableN;
or
datatype variable1;
datatype variable2;
datatype variableN;
- can give an initial value to a variable.
- Example:
int num = 10;
______________________________________________________________________________________
2
Fakulti Sains Komputer dan Matematik
Universiti Teknologi Mara, 40450 Shah Alam, Selangor
Basic C++ program
____________________________________________________________________________________
2.2.4. Constants
- Values that do not change during program execution.
- To declare a constant:
const datatype constantname = value;
Ex: const float pie = 3.142;
const constantname = value;
Ex: const pie = 3.142;
#define constantname value
Ex: #define pie 3.142
Variables can hold different types of data. C++ support seven built in data types and it identifies
them by keywords.
C++ provides an operator called sizeof() for determining the amount of storage compiler
allocates for each datatype:
Example: sizeof(int)
sizeof(char)
2.4 Operators
Arithmetics Operators.
Operation Operator
Addition +
Subtraction -
Multiplication *
Division /
Modulus Division %
- A simple arithmetic expression consist of:
operand operator operand
______________________________________________________________________________________
3
Fakulti Sains Komputer dan Matematik
Universiti Teknologi Mara, 40450 Shah Alam, Selangor
Basic C++ program
____________________________________________________________________________________
Relational Operators
Operator Meaning
< Less than
<= Less than or equal
> Greater than
>= Greater than or equal
== Equal
!= Not equal
Logical Operators
Operator Meaning
&& AND
|| OR
! NOT
Assignment Operator
- is =
- Normally used to assign value to a variable
- General form of assignment statement:
Variable = expression;
Where expression represents a constant, a variable , arithmetic
expression ,logical/relational expression or more complex expression.
______________________________________________________________________________________
4
Fakulti Sains Komputer dan Matematik
Universiti Teknologi Mara, 40450 Shah Alam, Selangor
Basic C++ program
____________________________________________________________________________________
Unary expression
operator operand
Ex: -(-7)
variable=expression;
Where expression represents a constant, a variable , arithmetic expression,
logical/relational expression or more complex expression.
Example:
number=20;
area = width * height
Example:
______________________________________________________________________________________
5
Fakulti Sains Komputer dan Matematik
Universiti Teknologi Mara, 40450 Shah Alam, Selangor
Basic C++ program
____________________________________________________________________________________
x=y=z=0;
Same as: x=0, y=0, z=0
Operator Example
+= sum+=10 sum=sum+10
-= Sum-=10 sum=sum-10
*= Sum*=10 sum=sum*10
/= Sum/=10 sum=sum/10
%= Sum%=10 sum=sum%10
An escape sequence begins with the backslash \ and is followed by one or more
special characters.
2.10. Manipulator.
Manipulator Action
setw(n) Set the field width to n
setprecision(n) Set the floating point precision to n places
setiosflags(flags) Set the format flags
dec Set output for decimal display
hex Set output for hexadecimal display
oct Set output for octal display
The following table lists the format flags for use with setiosflags()
Flags Meaning
ios::showpoint Always display a decimal point. In the absence of the
ios::fixed flag, a numerical value with a decimal point
is displayed with a default of 6 significant digits. If the
integer part of the number requires more than 6 digits
the display will be in exponential notation, unless the
ios::fixed flag is in effect. For example, the value
1234567. is displayed as 1.23457e6 unless the
ios::fixed is in effect. This flag has no effect on integer
______________________________________________________________________________________
6
Fakulti Sains Komputer dan Matematik
Universiti Teknologi Mara, 40450 Shah Alam, Selangor
Basic C++ program
____________________________________________________________________________________
values.
ios::showpos Display a leading +sign when the number is positive
ios::fixed Display the number in conventional fixed-point decimal
notaion that is with an integer and fractional part
separated by decimal point and not in exponential
notation
ios::scientific Use exponential notation on output
ios::dec Display as a decimal number (default)
ios::oct Display as an octal number
ios::hex Display as a hexadecimal number
ios::left Left justify output
ios::right Right justify output
Example 1:
cout<< setw(3)<<21
- The setw(3) field-width manipulator included in the stream of data passed to cout
is used to set the displayed field-width. The 3 in this manipulator sets the default
field-width for the next number in the stream to be three spaces wide
- This field-width setting causes the 21 to be printed in a field of three spaces,
which includes one blank and the number 21. By default integers are right-
justified within the specified field.
Example 2:
cout<<6<<endl;
cout<<18<<endl;
cout<<124<<endl;
cout<< “----\n”;
cout<<(6+18+124)<<endl;
output:
6
18
124
----
148
Example 3:
cout<<setw(3)<<6<<endl;
cout<<setw(3)<<18<<endl;
cout<<setw(3)<<124<<endl;
______________________________________________________________________________________
7
Fakulti Sains Komputer dan Matematik
Universiti Teknologi Mara, 40450 Shah Alam, Selangor
Basic C++ program
____________________________________________________________________________________
cout<<“----\n”;
cout<<(6+18+124)<<endl;
output:
6
18
124
----
148
- Formatting floating-point numbers require the use of three manipulators. The first
manipulator sets the total width of the display, including the decimal point. The second
manipulator sets the total width of the output type (exponent or conventional decimal
display). The third manipulator determines the number of digits can be printed to the right of
the decimal point(precision).
Example
cout<<”|”<< setw(10) <<setiosflags(ios::fixed)
<<setprecision(3)<<25.67<< “|”;
Output:
| 25.670|
- For all number (integers, floating-point and double), cout ignores the setw() manipulator
specification if the space specified field width is too small and allocates enough space for
the integer part of the number to be printed.
- The fractional part of both floating-point and double-precision numbers is displayed up to
the setprecision() manipulator. If the fractional part of the number contains more digits
than called for in the setprecision(), the number is rounded to the indicated number of
decimal places. Otherwise, it will be padded with trailing zeros.
- Flags that are not mutually exclusive, such as ios::dec, ios::showpoint, and ios::fixed can
all be set on at the same time. Thiscan be done using three individual setiosflag() calls or
combining all arguments into one call as follows:
cout<<setiosflags(ios::dec||ios::showpoint||ios::fixed);
- instead of using manipulators, you can also use the cout stream function setf() and
precision(). For example, the following formatting
cout<<setiosflags(ios::fixed)
<<setiosflags(ios::showpoint)
<<setprocision(2);
can also be accomplished using the code as follows:
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
2.12. Errors
- A program should be efficient, readable and error=free which works correctly and can be
modified or changed with a minimum of testing required for reverification.
- In this regard, it is useful to know the different types of errors that can occur, when they
are detected and how to correct them.
______________________________________________________________________________________
8
Fakulti Sains Komputer dan Matematik
Universiti Teknologi Mara, 40450 Shah Alam, Selangor
Basic C++ program
____________________________________________________________________________________
Computer literature distinguishes between two primary types of errors, called syntax and
logic errors.
Syntax error is an error in the structure or spelling of a statement. For example:
The statement above, contains four syntax errors. The errors are:
a. A closing quote is missing in line 1
b. A terminating semicolon(;) is missing in line 1
c. The keyword cout is misspelled in line 2
d. The insertion symbol is missing in line 2.
All of these errors will be detected by the compiler when the program is compiled. Thus,
syntax errors is also known as compile-time errors.
Basically, syntax errors are caused by the violation of the basic rules of C++.
Logic errors are characterized by erroneous, unexpected or unintentional errors that are a
direct result of some flaw in the program’s logic. The computer may not detect them,
therefore they are more difficult to detect than the syntax errors.
If the error is detected while the program is executing, a run-time error occurs that results in
an error message being generated and/or abnormal program termination.
Logic error causes the program to run properly but produces incorrect result such as:
a. No output: either caused by an omission of cout statement or a sequence of
statements that inadvertently by passes a cout statement.
b. Unappealing or misaligned output: this is caused by an error in a cout
statement.
c. Incorrect numerical results: caused by either incorrect values assigned to the
variables used in an expression, the use of incorrect arithmetic expression, an
omission of a statement, roundoff error, or the use of improper sequence of
______________________________________________________________________________________
9
Fakulti Sains Komputer dan Matematik
Universiti Teknologi Mara, 40450 Shah Alam, Selangor
Basic C++ program
____________________________________________________________________________________
statements.
Exercise:
See if you can detect the errors in the following program:
#include <iostream.h>
#include <iomanip.h>
#include <math.h>
int main()
{
float capital, amount, rate, nyrs;
C++ Operators
This table lists all the operators in C++, grouping them by order of precedence. The higher-
level precedence-operators are evaluated before the lower-level precedence operators. For
example, in the expression (a - b*c), the * operator will be evaluated first and the - operator
second, because * has precedence level 13 which is higher than the level 12 precedence of -, The
column labeled "Assoc." tells whether an operator is right associative or left associative. For
example, the expression (a - b - c) is evaluated as ((a - b) - c) because - is left associative. The
column labeled "Arity" tells whether an operator operates on one, two, or three operands (unary,
binary, or ternary). The column labeled "Ovrldbl." tells whether an operator is overloadable.
______________________________________________________________________________________
10
Fakulti Sains Komputer dan Matematik
Universiti Teknologi Mara, 40450 Shah Alam, Selangor
Basic C++ program
____________________________________________________________________________________
______________________________________________________________________________________
11
Fakulti Sains Komputer dan Matematik
Universiti Teknologi Mara, 40450 Shah Alam, Selangor
Basic C++ program
____________________________________________________________________________________
______________________________________________________________________________________
12
Fakulti Sains Komputer dan Matematik
Universiti Teknologi Mara, 40450 Shah Alam, Selangor
Basic C++ program
____________________________________________________________________________________
Exercises
1. Write C++ statements to declare and sum the three floating-point values gpa1, gpa2, and
gpa8. Then, calculate the average as purataGPA.
2. Write C++ statement to initialize a string as HELLLO. Then write a statement to display
the string.
3. Identify whether these are valid identifiers. For those which are invalid (if any) please
state your reason(s).
a. Nombor_nombor
b. Float
c. newsbulletin
d. myNewNombor
e. –news
f. nw&pepper
g. nEwWord
h. main
i. key word
j. character
Welcome.
Calculating the hypotenuse of a left-angled triangle.
Enter the length of the triangle side:
Enter the length of the triangle base:
Then, let user input the value for side and base. After that calculate the
hypotenuse. Use the formula:
( side) 2 (base) 2
hypo =
Then, display the value of side, base and calculated hypotenuse as below:
#include <iostream.h>
#include <math.h>
void main( )
{
int a = 11, c = 4, b;
double jumlah;
b = 20 + c;
c = ( b + 3 ) % c + 3;
cout<< “Value c is:” << c << “ and b is: ”<< b <<endl;
______________________________________________________________________________________
13
Fakulti Sains Komputer dan Matematik
Universiti Teknologi Mara, 40450 Shah Alam, Selangor
Basic C++ program
____________________________________________________________________________________
a = a + c;
jumlah = a / 2;
cout<< jumlah <<“ is the value of jumlah ” <<endl;
cout<<setw(3) <<x<<x_square;
cout<<setw(3)<<y<<y_square;
______________________________________________________________________________________
14
Fakulti Sains Komputer dan Matematik
Universiti Teknologi Mara, 40450 Shah Alam, Selangor