Basic Elements of Programming Language: Source of Notes: MR Jamal Othman
Basic Elements of Programming Language: Source of Notes: MR Jamal Othman
BASIC ELEMENTS OF
PROGRAMMING LANGUAGE
6) Assignment expression
8) Assignment statement
a) By referring the above simple program, there are several identifiers are detected. The words
include, iostream, int, main, cout, {, } are considered as identifiers.
b) So another word is there are many identifiers will be used when you write programs. Identifier
is also related with variable and constant. An identifier in C++ is case sensitive. For example,
the identifier Sum is not the same identifier as sum or SUM.
http://oakroadsystems.com/tech/c-predef.htm#Table
http://www.acm.uiuc.edu/webmonkeys/book/c_guide/index.html
What is Header File?
Each program must contain the header file or library. Eg : iostream.h, iomanip.h, math.h,
conio.h, string.h. If the header file is not included, the program will contain many errors.
What are Variables?
a) Variables also referred to as "identifiers" are named memory locations that have a
type, such as an integer or character, and consequently, a size, which is inherited
from their type.
b) Since variables are types, they have a set of operations that can be used to change
or manipulate them.
Numbers - 0 through 9.
f) There are some reserved words in C++, so the programmer should be cautious
in his choice of identifier names. For example, "int" is a poor choice, since that
is a reserved word indicating the type of the variable.
h) Samples of variable:
Meaningful
Understandable
Avoid ambiguity
Variable Valid/Invalid
TotalNum
int
VOID
sum Num
aVeraGe32
#area
Discount*price
plus987abc
Exercise on naming variables:
Answers:
Variable Valid/Invalid
TotalNum Valid
int Invalid
VOID Valid
sum Num Invalid
aVeraGe32 Valid
#area Invalid
Discount*price Invalid
plus987abc Valid
Variable Types
Refer to any text for a complete set of variable types. Here is a short list of commonly
used types.
char A 1 byte integer usually used to store a character.
short A 2 byte integer.
int A 4 byte integer.
long 4 or 8 byte integer (compiler dependent).
Single precision floating point number.
float
(7 digits or more - compiler dependent)
Example:
int age; //Declare age as integer.
float sum; //Declare sum as float.
double area; //Declare area as double
char name[25]; //Declare name as character.
string address=""; //Declare address as string.
char gender; //Declare gender as character.
Sample program using integer data type:
#include <iostream>
using namespace std;
int main()
{
int value1, value2;
value1 = 4;
value2 = 5;
cout << value1 << value2;
return 0;
}
This program shows the usage of integer data type. Two variables have been declared value1 and
value2. Both data type is integer. Means both variables accept numbers only.
If we relates to the concepts of memory management, there are two addresses have been used to
Eg:
4 5
value1 value2
Sample program using float data type:
#include <iostream>
using namespace std;
int main()
{
float pai;
pai = 3.14;
cout << pai;
return 0;
}
Others examples of variable using float are currency, GPA, CGPA and etc.
Sample program using double data type:
#include <iostream>
using namespace std;
int main()
{
double result;
result = 3.263772838;
cout << result;
return 0;
}
This program shows that the variable use double data type.
They are two types of char, either you enter an alphabet/symbol or string.
Example:
const double PAI = 3.142;
Basic Arithmetic Operators
Basic arithmetic's operators are:
Arithmetic
Operators Arithmetic Operation Example
in C++
Example:
a * (b+c)
a) 1-(1-(1-(1-n))) = 9
you must solved in the bracket first then go to outer bracket.
b) m / n + n % m
m / n = 1 then n % m = 9 , the final answer is 10
c) - m + sqrt (n * n – a * m ) / 2 * a
sqrt (n * n – a * m ) = 7
then divide by 2 = 3
then * a = 6
- m + 6 = -10
Exercise on Precedence & Associativity
Exercise on Precedence & Associativity
Writing Program (Exercise)
Write a program that ask the user to enter two integers.
Then, compute the addition, substraction, multiplication and
division of the two integers. The program will display the
output of all the mathematical operations above.
Commenting the Program
1) Comment is very important in any program.
2) The purpose of commenting the program is to:
make us easier to refer and
understand the function of the program.
3) Normally the program will consists like author’s name, date program created,
purpose, etc.
Example:
//Author : Aminah Bt Abu Bakar
//Date : 7 May 2002
//Purpose : to calculate the total of two numbers
#include <iostream>
using namespace std;
int main()
{
int a, b;
a=5;
b=6;
cout << a+b;
return 0;
}
Input and Output Statements
Among the statements in sequential structure in C++:
Example:
mark = 3; //assigning an integer value
grade = ‘A’; //assigning a character value
strcpy(name, “Aziz”); //assigning a string value
total = 33.5; //assigning a double value
courseCode = “CSC128”; //assigning a string value
Assignment Statement (cont…)
1) A variable can store only one value at a time.
Example:
number = 12.7;
number = 35.2;
• The value 12.7 will be assigned to variable number and then the value
35.2 will be assigned to variable number. The value 12.7 will be
overwrite and number would retain the latest value 35.2.
Assignment Statement (cont…)
2) Two variables can also store the same value.
Example:
int number1, number2;
number1 = 12.7;
number2 = number1;
Example:
int count;
int main()
{
int x = 10, y = 5;
cout << x << " " << y << endl;
cout << ++x << " " << ++y << endl; // prefix
cout << x << " " << y << endl;
cout << x++ << " " << y++ << endl; // postfix
cout << x << " " << y << endl;
cout << x-- << " " << --y << endl; // postfix & prefix
cout << x << " " << y << endl;
return 0;
}
Mathematical Library Functions
All the arithmetical function from #include<math.h> header file are listed in the
following table:
Function name Operation
sqrt() Return the square root of the argument
pow(x,y) Return x raised to the power of y
pow10(y) Return 10 raised to the power of y
sin() Return the sine of argument (radiant)
hypot(a,b) Return the hypotenuse of a right triangle whose sides are a and b
tan() Return the tangent of the argument (radians)
log() Return the natural log of the argument
Log10() Return the base 10 log of the argument
abs() Return the absolute value of argument
Sample program using sqrt and pow function:
#include <iostream>
using namespace std;
#include <math.h>
int main()
{
int number, power;
double squareroot;
squareroot = sqrt(number);
power = pow(number,2);
return 0;
}
Input Statement
Data to be keyed-in through keyboard
Example:
a) Used for numbers (int, long, float, double) or a single character (single-char)
cin >> variable_name;
cin >> value1;
//output a character
cout << ‘A’;
Example:
\n Newline.
\t Horizontal tab.
\r Carriage return.
\a Alert sound (bell).
\\ Outputs a backslash character.
\" Outputs a double quote character.
endl means “end-of-line” is used to move the cursor to the next line right after
that word.
Formatting Output (cont…)
I/O Manipulator
#include <iostream>
using namespace std;
#include <iomanip>
#include <string.h>
int main()
{
cout<<“\n” // skip a line
<<setw(30)<<“STUDENTNAME” // display heading
<<setw(15)<<“MATRICNO”
<<setw(10)<<“PROGRAMME”<<endl;
return 0;
}
Formatting Output (cont…)
Example of using setw (n):
number = 101.75;
cout << setw(10) << setfill(‘*’) << number;
****101.75
cout.setf(ios::fixed);
cout.precision(n);
Example:
int number = 101.75123;
cout.setf(ios::fixed);
cout.precision(2);
cout<<number;
By default, when we use setw(n) to print values or information, the values are
right justified.
In order to change the default, to put the outputs as left justify, we must write
this statement:
cout.setf(ios::left);
Formatting Output (cont…)
Generating Left-Justified Value
Example Program:
#include<iostream>
using namespace std;
#include<iomanip>
#include<string.h>
int main()
{
string name1="";
string name2="";
string prog1;
string prog2;
cout.setf(ios::left);
cout<<"\n\n";
cout<<setw(50)<<"NAME"<<setw(10)<<"PROGRAMME"<<endl;
cout<<setw(50)<<"----"<<setw(10)<<"---------"<<endl;
//display values
cout<<setw(50)<<name1<<setw(10)<<prog1<<endl;
cout<<setw(50)<<name2<<setw(10)<<prog2<<endl<<endl;
return 0;
}
Formatting Output (cont…)
Generating Left-Justified Value
Compile
button
Programming Process, Debugging and
Error Handling (cont…)
Once compiled, any error (s) in the program will be displayed at the bottom of the
application as below.
The program statement which contains error will be automatically highlighted.
Error(s)
Programming Process, Debugging and
Error Handling (cont…)
After corrections are done to the program (with errors), press compile button again
and your program is ready to be run if there are free from any errors (refer the
sample below).
No more
errors
Programming Process, Debugging and
Error Handling (cont…)
Click run button to display your output screen.
Run
button
Programming Process, Debugging and
Error Handling (cont…)
Types of Error
Question:
Calculate the subtraction and multiplication of two numbers.
Steps in problem solving:
1) To understand the following question, the first step, this question means that you
have to enter any two numbers and get the subtraction and multiplication of two
numbers.
2) The second step identifying the input, process and output.
Input : a, b
Process : subtract = a – b, assuming a always bigger than b
multiply = a * b
Output : subtract and multiply
Example of Sequential Control Structure (cont...)
BEGIN
ENTER first number(a) and second number(b)
CALCULATE subtract = a – b
CALCULATE multiply = a * b
DISPLAY subtract, multiply
END
Example of Sequential Control Structure (cont...)
BEGIN
ENTER a and b
if a > b
DISPLAY a is greater than b
if b > a
DISPLAY b is greater than a
if a==b
DISPLAY a equal to b
END
Example of Selection Control Structure (cont...)
BEGIN
ENTER any number (a)
while a not equal to 99
DISPLAY a
otherwise program will stop
END
Example of Iteration/Loop Control Structure (cont...)