0% found this document useful (0 votes)
7 views9 pages

BASIC ELEMENTS OF COMPUTER PROGRAMS Part 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views9 pages

BASIC ELEMENTS OF COMPUTER PROGRAMS Part 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

BASIC ELEMENTS OF COMPUTER PROGRAMS (Part 2)

4. VARIABLE AND CONSTANT DECLARATION


4.1 VARIABLE DECLARATION
The process of clarifying the variable name and data type of a variable is known as variable
declaration. As explained earlier, all the variables and constant variables must be declared. The
declaration is a C++ statement, so it should end with a semicolon (;).We should write the data
type in the declaration statement, followed by the variable name.
The general way to write a variable declaration is as follows:
Data type variable_name;
Examples:

• int age;
• double total_Price;
• char gender;
• bool status;
• string name;
When writing the declaration statement, the correct data type for the variable defined in
our problem statements must be determined. Giving suitable variable names relevant to the
problem statement is also good practice. These requirements will make the resulting program
easy to understand.
4.2 CONSTANT VARIABLE DECLARATION
Constant variables must also be declared before they can be used. As mentioned earlier, all
variables must be declared before they are used in a program. As we know, a constant variable
is a variable that has a value that never changes. So, we have to clarify the value once we declare
it, as the computer will use it as we have declared.
To declare the constant variable, we will use the literal value, which means that we are using the
constant value. A literal value is any fixed or constant value used in a program. To write the
declaration statement for a constant variable, we will write starting with const and continue with
the data type and variable name and assign the literal or actual value of the variable to it.
The syntax of a declaration statement for a constant variable is:
const data type variable name = literal or actual value;
Examples:

• const double PI=3.142;


• const string companyName= “ABC Enterprise”;

5. ARITHMETIC EXPRESSIONS
5.1 ARITHMETIC OPERATORS
Arithmetic expressions are the mathematical formula used to solve the problem statement.
Usually, in solving a problem, we will do some calculations or evaluations to find the solution. In
C++ programming, a few operators are defined in the arithmetic expressions.
There are five (5) basic operators used in C++ expressions. They are addition (+), subtraction (-),
multiplication (*), division (/), and modulus (%).
To write an arithmetic expression or mathematical formula in C++ programming, we will write
the expression with the operator and continue with the assignment operator (=). A semicolon
should be placed at the end of each arithmetic expression.
Example:
ANS = X + Y;
The following example shows an arithmetic expression to add variable x to variable y and
store the answer in the variable ANS.
Process Symbol/Operators Example
Addition + 40.5 + 2.2 = 42.7 or 28 + 5 = 33
Subtraction - 60 – 30 = 30 or 50.2 – 20 = 30.2
Multiplication * 7 * 3 = 21 or 10.5 * 3 = 31.5
Division / 6 / 3 = 2 or 10.0 / 3 =0.3333
Modulus (remainder) % 29 % 9 = 2 or 8 % 2 = 0
Never use modulus with a floating point values
A summary of explanations and examples for C++ expressions

Algebraic Expression C++ Arithmetic Expression


14 – 10 + 63 14 – 10 + 63
56 – 9
56 – 9/2
2
16 + 3 + 85
(16 + 3 + 85) / 2
2
53 5*5*5 or pow(5,3)
Conversion of algebraic expression to C++ arithmetic expression
5.2 ASSIGNMENT STATEMENT
An assignment operator (=) is an operator that shows where the value is assigned to. If given x=5,
the value 5 is stored by variable x. Every variable in a program is given a value explicitly before
any attempt is made to use it. It is also very important that the value assigned is of the correct
type. The most common form of statements in a program uses the assignment operator (=) to
show an expression or even assign value to variables and as shown in the following examples:
a= b + c; // expression
x = 5; // assigning value to variable x
const double PI=3.142; // assign value to constant
Assigning values to variables is called initialize. Initialization is the process of assigning a first value to a
variable. In C++, all variables must be explicitly initialized. Sometimes, the declaration statement and
initialization can be combined into one statement as shown in the following example:

double price + 37.99;

OR

double price;

price = 37.99;

// a variable named price is declared as a double data type, and now the memory cell named price contains
the value 37.99

Besides simple assignment (=), we also have a situation of (==) whereby this assignment is used
to do a comparison between the right and left sides of assignments (==). For example, in the selection
type of program, we need to do a comparison of the answer that the user keys in with the defined value,
especially values using char and string data type as shown below:

If (ans==’y’)

True statements;

Else

False statements;

More examples:

X=3; // means value of 3 is assigned to x variable


X==3; // means checking whether x is equal to 3 or not

The compound assignment is another term that shows we need to perform the calculation based
on the expression given.

Operator Example Meaning


+= total + = 2 total = total + 2
- = Total - = 2 total = total - 2
*= total * = 2 total = total * 2
/= total / = 2 total = total / 2
%= total % = 2 total = total % 2
C++ compound assignments

5.3 PRECEDENCE AND ASSOCIATIVITY


Precedence means a sequence of arrangements or order of operations that should be performed
first. In C++, we routinely have a few operators in a mixed expression. Which one should be
evaluated first? Here, we must follow the precedence rules to perform the mixed expression. We
have to solve the expression based on the highest priority.
Associativity is a process whereby it specifies the order if the operators have the same priority. If
the operators have the same priority, then we will perform the calculations from left to right.
Operator(s) Operation Precedence
() Parentheses Evaluated first, inside-out if
nested, or left to right if the
same level
*, /, % Multiply, Divide, Modulus Evaluated second, left to right
+, - Add, Subtract Evaluated last, left to right

Examples:

1. 2 + 2 * 5
Solution:
2 + (2 * 5)
= 2 + 10 // evaluate *
= 12 // evaluate +

2. 2 * 3 / 2 % 2
Solution: // evaluate operators from left to right
= 6 /2 // evaluate *
= 3 % 2 // evaluate %
=1
5.4 INCREMENT AND DECREMENT OPERATORS (POSTFIX AND PREFIX)
The increment is the process of adding value; the decrement subtracts value in a statement.
Usually, incremental and decremental expressions will be used in looping. Postfix means we will
perform the expression after the evaluation. Prefix means we will perform the evaluation
immediately.
The table below shows how increments and decrements for postfixes and prefixes are calculated.

Operator’s Name Operator Meaning


Increment postfix a++ a=a+1
Increment prefix ++a a=a+1
Decrement postfix a-- a=a-1
Decrement prefix --a a=a-1
List of incremental and decremental operators(postfix and prefix expressions)
Examples:

Increment expression Decrement expression


Given a = 4 Given a = 4
a++ a--
it means: a = a + 1 it means: a = a - 1
=4+1 =4-1
=5 =3

Given a = 4 Given a = 4
++a --a
It means: a = a + 1 It means: a = a - 1
=4+1 =4-1
=5 =3

6. MATHEMATICAL LIBRARY FUNCTIONS


Besides the five basic operators in arithmetic expressions, other mathematical operators are
defined in the mathematical library function. For example, the algebraic expression x2 means x
power of 2.
We have to refer to the maths library functions to use those operators. While writing the
program, we need to include the math.h header file that will allow the computer to refer to the
library.

Function Operation
sqrt(x) Returns the square root of the argument x
pow(x,y) Returns x raised to the power of y
pow10(y) Returns 10 raised to the power of y
sin( ) Returns the sine of argument (radians)
hypot(a,b) Returns the hypotenuse of right triangle with sides a and b
log( ) Returns the natural log of the argument
log10( ) Returns the base 10 log of the argument
abs( ) Returns the absolute value of the argument
List of predefined functions in the maths library
Example:

// Program to calculate and show the application of the maths library function

// Header files

#include<iostream>

#include<math.h>

using namespace std;

// Main function

int main( )

{ //program starts

int number1=5, power; //declarations and initialization value

power=pow(number1,2); //calculate power of 2 for the number

cout<<”Number=”<<number1<<endl;

cout<<”Power 2 of the value=”<<power<<endl;

return 0;

} //program ends

----------------------------------------------

Output:

Number = 5

Power 2 of the value = 25


7. INPUT AND OUTPUT STATEMENTS
After the declaration steps, we will continue reading data from the user, also known as the input
process. As discussed earlier, in the input process, we use the input variable. The input process
can be done in two ways. Firstly, by assigning the value to the variable, and the second way is by
reading the value from the user. The standard input stream, cin, is used to represent the input
statement. The cin statement is used to get input from the user using the keyboard.
To perform the read process in a C++ statement, we will use the syntax below:
cin>>input variable name;
Example:

cin>>num1;
cin>>code;
The examples above show how to read a numeric data type.
For char [ ] that has more than 1 value and string data type, we need to include the string header
to allow the process to be executed. The reading process will have getline keyword whereby the
the keyword will inform the computer to accept the string value. The reading process for char [ ]
and string data type can be performed using the general syntax as shown in the following
example:
cin.getline(variable, length); // for char with size
getline(cin,name); // for string data type

Example 1:
//Program to read char data type
//header files
#include<iostream>
using namespace std;

//main function

int main( )

char student_name [10];

//ask to input string


cout<<”Please enter your name:”

cin>>ws;

cin.getline(student_name, 10);

return 0;

} // program ends

Example 2:

//Program to read string data type


//header files
#include<iostream>
using namespace std;

//main function

int main( )

string student_name;

//ask to input string

cout<<”Please enter your name:”

cin>>ws;

getline(cin,student_name);

return 0;

} // program ends

For display instructions and outputs in C++, we will use the cout statement. For display
instructions, we will write the instruction in double quote after the cout<< and end the statement with
the semicolon (;). The syntax of the display instruction is shown below:

cout<< “instruction statements”;

For display output in C++, we will use the cout statement, place the variable name, and end the statement
with a semicolon (;). The syntax of the display output is as follows:
cout<< output variable name;

If we want to combine an instruction and display output in one statement. It can be written like this:

cout<<”instruction statements”<< variable name;

Example:

//Program to display instruction and output


//header files
#include<iostream>
using namespace std;

//main function

int main( )

// declare and assign value to the variable

int age;

age = 25;

string name = “Allan”;

// display string

cout<<”Hi, my name is:”<<name<<endl;

// display value

cout<<”I am “<<age<<”years old”<<endl;

cout<<6*2+5; // displaying expression value

cout<<pow(5,2); // displaying mathematical function

return 0;

} // program ends

You might also like