You are on page 1of 14

Basic C++ program

____________________________________________________________________________________

CHAPTER 2 Introduction to C++ Programming.


Why C++?
 Very useful language that gives the programmer a lot of control but also is abstract enough,
therefore the development can be done fairly quickly.
 Very portable, well defined set of standards code written
 Advantages of using C++:
 Allows expression of abstract ideas
 Still allows a programmer to keep low-level control eg memory management
 Reusable and object-oriented
 Widely used and taught

2.1 The General Structure of C++ program

#include<iostream.h>

// This is main stucture of C++ program


/* C++ is a high-level language
with object-oriented */

int main()
{
cout<<” Hello World”;
return 0;
}

 Preprocessor Command - #include


- The #include directive is necessary for the program to have output and input.
- Refers to an external file namely iostream.h (header file) where information
about the cout and cin object is provided. In particular, the iostream.h file provide
descriptions of two classes, istream and ostream.
- <> angle bracket to indicate that this is a standard C++ library file.
- Preprocessor commands do not end with a semicolon.

 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 main() function


- Each C++ program must have one and only function named main().
- Referred as a driver function because it drives and tells the sequence of a
program.
- First line of the function int main() referred as function header. It contains 3
pieces of information:
a. what type of data, if any, is returned from the function.
b. Name of the function.
c. What type of data, if any, is sent into the function.
______________________________________________________________________________________
1
Fakulti Sains Komputer dan Matematik
Universiti Teknologi Mara, 40450 Shah Alam, Selangor
Basic C++ program
____________________________________________________________________________________

- 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 (;) .

 return statement ( return () )


- Return control to the operating system.
- To signal end of function.

 String Literals.
- The statements “Hello World” is called string literals.
- It consist sequence of characters delimited by quotation marks.

2.2 Identifiers, Variables, Constants and Keywords.

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

2.3. Basic Data Types

Variables can hold different types of data. C++ support seven built in data types and it identifies
them by keywords.

Data Type C++ Bits Range


Keyword
Integer int 16 -32768 to 32767
Long integer long 32 -4294967296 to 4294967295
Short integer short 8 -128 to 127
Unsigned integer unsigned 16 0 to 65535
Character char 8 0 to 255
Floating-point float 32 6 digit precision
Double floating point double 64 12 digit precision

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.

Unary Operator (negation)


- unary operator uses the same symbol that is used for subtraction.
- The minus sign used in front of a single numerical operand negates(reverse) the
sign of the number.
Increment operator(++)
- it is a unary operator
- prefix increment operator and postfix increment operator.
- Prefix=operator appears before variable
- Ex: ++k
- If sum=++k its mean k=k+1; sum=k
- Postfix=operator appears after variable.
- Ex: k++
- If sum=k++ its mean sum=k; k=k+1
-
Decrement operator(--)
- it is a unary operator
- prefix decrement operator and postfix decrement operator.
- Prefix=operator appears before variable
- Ex: --k
- Postfix=operator appears after variable.
- Ex: k—

______________________________________________________________________________________
4
Fakulti Sains Komputer dan Matematik
Universiti Teknologi Mara, 40450 Shah Alam, Selangor
Basic C++ program
____________________________________________________________________________________

2.5 Hierarchy of Operators.

The hierarchy of operator precedence (priority) from highest to lowest:

Operator Category Operator


Unary - , ++ , -- *right to left
Multiply, divide, remainder *, / , % *left to right
Add and subtract +, - *left to right
Relational Operators <, <=, >, >=
Equality Operators ==, !=
Logical AND &&
Logical OR ||

2.6. Arithmetic Expression.


General format
operand operator operand
Ex: 3 + 9

Unary expression
operator operand
Ex: -(-7)

2.7. Expression Types.


1. Integer expression
- expression that contains only integer operand
- result is an integer value.
2. floating-point expression
- expression that contains only floating-point operand.
- Result is a floating-point value.
3. mixed-mode expression
- expression that contains different data types.
- They are converted to the biggest data type.

2.8. Assignment Statement and Its Variations.

variable=expression;
Where expression represents a constant, a variable , arithmetic expression,
logical/relational expression or more complex expression.

Type 1: simple assignment (assign a value or formula written)

Example:
number=20;
area = width * height

Type 2: Multiple assignment

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

Type 3: Shortcut Assignment Operators

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

2.9. Escape sequences.

An escape sequence begins with the backslash \ and is followed by one or more
special characters.

Code Meaning Code Meaning


\a Audible bell \t Horizontal tab
\b Backspace \\ Backslash character
\f Formfeed \’ Single quote character
\n Newline \” Double quote character
\r Carrige return \0 NULL ASCII 0

2.10. Manipulator.

- A header file must be include namely iomanip.h


- Besides displaying correct results, it is extremely important for a program to
present its output attractively. The format of displaying output can be controlled
using 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

2.11 Formatted Output

o Using input output manipulator to display the numerical values according


certain format.
o Must use iomanip.h library file that stored many built in function that
can be applied in formatting the values

2.11.1. Formatting Integer Values

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

2.11.2 Formatting Floating-point Numbers

- 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
____________________________________________________________________________________

2.12.1 Compile-Time and Run-Time Errors

A program error can be detected at a variety of times:


a. Before a program is compiled
b. While the program is being compiled
c. While the program is being run
d. After the program has been executed and the output is being examined
e. Not at all
 Errors detected by the compiler are formally referred to as compile-time errors
 Errors that occur while the program is being run are formally refereed to as run-
time errors.
 Program verification and testing is a method that can be carried out to detect
error after the program has been executed.
 Desk checking is a method for detecting errors before compiling the program.
 Debugging programs is a method to detect for error while a program is being
executed.

2.12.2. Syntax and Logic Errors

 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:

cout << “there are 4 syntax errors here\n


cot “Can you find tem”;

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;

cout << “This program calculates the amount of money\n”;


cout << “in a bank account for an initial deposit \n”;
cout << “invested for n years at an interest rate r.\n\n”;
cout << “Enter the initial amount in the account : “;
cin >> amount;
cout << “Enter the number of years: “;
cin >> nyrs;
capital = amount * pow ((1+rate/100/0, nyrs);

cout << setiosflags (ios::fixed)


<< setiosflags (ios::showpoint)
<< setprocision (2);
cout << “\n The final amount of money is “
<< setw(8) << ‘$’ << capital << endl;
return 0;
}

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.

Op Description Prec. Assoc. Arity OvrldbI. Example


:: Global scope resolution 17 Right Unary No ::x
:: Class scope resolution 17 Left Binary No X::x
. Direct member selection 16 Left Binary No s.len
-> Indirect member selection 16 Left Binary Yes p->len

______________________________________________________________________________________
10
Fakulti Sains Komputer dan Matematik
Universiti Teknologi Mara, 40450 Shah Alam, Selangor
Basic C++ program
____________________________________________________________________________________

[] Subscript 16 Left Binary Yes a[i]


() Function call 16 Left N /a Yes Yes
() Type construction 16 Left N/a Yes int(ch)
++ Post-increment 16 Right Unary Yes n++
-- Post-decrement 16 Right Unary Yes n--
sizeof Size of object or type 15 Right Unary No sizeof(a)
++ Pre-increment 15 Right Unary Yes ++n
-- Pre-decrement 15 Right Unary Yes --n
~ Bitwise NOT 15 Right Unary Yes ~s
! Logical NOT 15 Right Unary Yes !p
+ Positive 15 Right Unary Yes +n
- Negative 15 Right Unary Yes -n
* Dereference 15 Right Unary Yes *p
& Address 15 Right Unary Yes &x
new Allocation 15 Right Unary Yes new p
delete Deallocation 15 Right Unary Yes delete p
() Type conversion 15 Right Binary Yes (int)ch
.* Direct member selection 14 Left Binary No x. *q
->* Indirect member selection 14 Left Binary Yes p->q
* Multiplication 13 Left Binary Yes m*n
/ Division 13 Left Binary Yes m/n

Op Description Prec. Assoc. Arity Ovrldbl. Example


% Remainder 13 Left Binary Yes m%n
+ Addition 12 Left Binary Yes m+n
- Subtraction 12 Left Binary Yes m-n
<< Bit shift left 11 Left Binary Yes cout << n
>> Bit shift right 11 Left Binary Yes cin >> n
< Less than 10 Left Binary Yes X<y
<= Less than or equal to 10 Left Binary Yes x <= y
> Greater than 10 Left Binary Yes x>y
>= Greater than or equal to 10 Left Binary Yes x >= y
== Equal to 9 Left Binary Yes x == y
!= Not equal to 9 Left Binary Yes x!= y
& Bitwise AND 8 Left Binary Yes s&t
^ Bitwise XOR 7 Left Binary Yes S^t
| Bitwise OR 6 Left Binary Yes S|t
&& Logical AND 5 Left Binary Yes u && v
|| Logical OR 4 Left Binary Yes U||v
?: Conditional expression 3 Left Ternary No u?x:y
= Assignment 2 Right Binary Yes n = 22
+= Addition assignment 2' Right' Binary Yes n += 8

______________________________________________________________________________________
11
Fakulti Sains Komputer dan Matematik
Universiti Teknologi Mara, 40450 Shah Alam, Selangor
Basic C++ program
____________________________________________________________________________________

-= Subtraction assignment 2 Right Binary Yes n -= 4


*= Multiplication assignment 2 Right Binary Yes n *= -1
/= Division assignment 2 Right Binary Yes n /= 10
%= Remainder assignment 2 Right Binary Yes n %= 10
&= Bitwise AND assignment 2 Right Binary Yes s &= mask
^= Bitwise XOR assignment 2 Right Binary Yes S^= mask
|= Bitwise OR assignment 2 Right Binary Yes S|= mask
<<= Bit shift left assignment 2 Right Binary Yes s << 1
>>= Bit shift right assignment 2 Right Binary Yes s >>1
throw Throw exception 1 Right Unary Yes throw ( 22 )
, Comma 0 Left Binary Yes ++m,--n

______________________________________________________________________________________
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

4. Write algorithm that display the following prompts:

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:

Base Side Hypotenuse

5. Trace the following program and determine the output.

#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;

6. Assuming the line


cout << setiosflags (ios::showpoint | ios :: fixed);
has already been executed, what exactly will the output look like? (Show
all blanks precisely)
a. if radius = 4.5;

cout<<" The value of pi is "<<setprecision(6)<<pi<<endl;


cout<<" The value of radius is " <<radius<<endl;

b. (assume setprecision(6) is not in effect)


if x = 4, x_square = 16, y = 10, y_square = 100

cout<<setw(3) <<x<<x_square;
cout<<setw(3)<<y<<y_square;

7. a. Write an output statement to display a floating-point value of width six,


accurate to three decimal places
b. Write an output statement to display an integer of width 10 followed by a floating
point value of width 10, accurate to one decimal place.

______________________________________________________________________________________
14
Fakulti Sains Komputer dan Matematik
Universiti Teknologi Mara, 40450 Shah Alam, Selangor