Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

Variable Declaration

Constant Declaration

Input / Output Statements

Assignment Statements

The Sequence of a Complete Program

Mathematical Operators, Operands and Expressions


• Variable is a memory location whose content may change during
program execution.
• Variable declaration is a process of clarifying the variable name
and data type of a variable.
• The syntax for declaring one variable or multiple variables:
dataType identifier1, identifier2, …;

eg: int x, y;
double amountDue; Good programming practice:
char name[30]; ➢ Can declare and initialize
at the same time
Eg. int num1 = 10;
• Constant is a memory location whose content is not allowed to
change during program execution.
• Once the variable is declared constant, the value cannot be
changed, and variable cannot be assigned to another value.
• The syntax for declaring a constant:
const dataType identifier = value;

eg: const int noOfStudents = 30;


const float Pi=3.14;
const double conversion = 2.54;
const char blank = ‘ ‘;
Using a named constant to store fixed data, rather than using the data value itself.
TWO (2) major advantages:

➢ When the fixed data changes, you do not need to edit the entire program and
change the old value to the new value whenever the old value is used. Instead, you
can make the change at just one place, recompile the program, and execute it using
the new value throughout.
➢ In addition, by storing a value and referring to that memory location whenever the
value is needed, avoid you typing the same value again and prevent accidental typos.
If you misspell the name of the location, the computer will warn you through an error
message, but it will not warn you if the value is mistyped.
• Name must begin with a letter or underscore.
• Name must contain only letters, numbers and underscore.
• Recommend length of the name is 3 – 8 characters.
• Name cannot be reserved word/keyword.
• Should use descriptive name to describe the purpose of that identifier/variable.
• Eg:
Valid Name Invalid Name
deposit 98deposit
end_bal end bal
withdrawal withdrawal.amt
privatelocation private
• Standard input stream is called cin, which will pause the program to allow the user to enter
the data.
• Symbol >> that follows after cin is called extraction operator means “gets from”.
• The syntax of cin together with >> is:
cin >> variable >> variable …;

• Eg: cin >> num1;


(gets the value from the keyboard then stores it in memory location name num1).
• More examples using input statement: Task Sample statement
To input numeric data type int num1, num2;
cin >> num1 >> num2;
To input a character data type char letter;
cin >> letter;
To input a string of characters char text[6];
cin.getline(text, 6);
• Standard output stream is called cout which refers to the computer screen.
• Symbol << that follows after cout is called insertion operator means “sends to”.
• The syntax of cout together with << is:
cout << expression or manipulator << expression or manipulator …;
• Eg: cout << “The sum of the number is “ << sum;
(sends the “The sum of the number is “ message and the contents of variable sum to
computer screen).
• More examples using output statement:
Task Sample statement
To display message cout << “Enter the number: “;
To display a value stored in a variable cout << total;
cout << “The area of square is: “ << area;
To display result from arithmetic expression cout << length * width;
cout << 20/5;
To display a formatted output using escape sequence cout << “This is the first line. \n\n This is the second line”;
Example 1: Example 2:
#include <iostream.h> #include <iostream.h>
using namespace std; using namespace std;
main () const float taxRate = 2.5;
{ main ()
float length, width; {
cout << "Enter the length and width: float salary, incomeTax;
"; cout << "Enter your salary: ";
cin >> length >> width; cin >> salary;
cout << "The length is " << length; incomeTax = salary * (taxRate/100);
cout << "\nThe width is " << width; cout << "\nThe income tax is RM " <<
incomeTax;
system(“pause”); system(“pause”);
} }
Output : Output :
Enter the length and width: 10 20 Enter your salary: 4000
The length is 10 The income tax is RM 100
The width is 20
Example 1: Example 2:
#include <iostream.h> #include <iostream.h>
using namespace std; using namespace std;
main () main ()
{ {
cout << "The total price is \nRM 101.11"; cout << "The total price is \tRM 101.11";
system(“pause”); system(“pause”);
} }

Output : Output :
The total price is The total price is RM 101.11
RM 101.11
• Use stream manipulators library (iomanip) and must be included in the preprocessor
directive command
• eg : #include <iomanip>
• Commonly used numeric formatting:
Manipulators Action
setw(n) Set the field width to n – Example 1
setprecision(n) ▪ Display the value with n number(s) – Example 2
▪Set the decimal point precision to n places (if using with
setiosflags(ios::fixed) – Example 6
setioflags(ios::fixed) Display the number in conventional fixed-point decimal
notation (6 floating points) – Example 3
setiosflags(ios::showpoint) Display a decimal point of that number (4 floating points) –
Example 4
setfill(‘x’) Fill the unused field width with ‘x’ character – Example 7
Example 1: Example 2:
#include <iostream.h> #include <iostream.h>
#include <iomanip> #include <iomanip>
using namespace std; using namespace std;
main () main ()
{ {
cout << "*" << "Hi there!" << "*" << endl; float real = 12.2256;
cout << "*" << setw(20) << "Hi there!" << "*" cout << setprecision(2) << real << "\n";
<< endl; cout << setprecision(4) << real;
cout << "*" << setw(3) << "Hi there!" << "*"
<< endl; system(“pause”);
}
system(“pause”);
Output :
}
12
Output : 12.23
*Hi there!*
* Hi there!*
*Hi there!*
Example 3: Example 4:
#include <iostream.h> #include <iostream.h>
#include <iomanip> #include <iomanip>
using namespace std; using namespace std;
main () main ()
{ {
float real = 12.2288666; float real = 12.22886;
cout << setiosflags(ios::fixed) << real << "\n"; cout << setiosflags(ios::showpoint) << real;

system(“pause”); system(“pause”);
} }
Output : Output :
12.228867 12.2289
Example 5:
:
float real = 12.2288666;
What will happen if you change the cout << setiosflags(ios::showpoint) << real << "\n";
position of these two instructions? cout << setiosflags(ios::fixed) << real << "\n";
: Output :
12.2289
12.228867
Example 6:
#include <iostream.h>
#include <iomanip>
using namespace std; The output will be same if the code is written as follows:
main () { cout << setprecision(2) << setiosflags(ios::fixed) << real ;
float real = 12.2288666;
cout << setiosflags(ios::fixed) << setprecision(2) << real << "\n";
system(“pause”);
} Example 7:

Output : #include <iostream.h>


12.23 #include <iomanip>
using namespace std;
main () {
float real = 12.2288666;
cout << "RM" << setfill('*') << setw(7) << setiosflags(ios::fixed)
<< setprecision(2) << real;
system(“pause”);
}
Output :
RM**12.23
• Use string predefined functions (cstring) and must be included in the preprocessor
directive command. → eg: #include <cstring>
• String input statement
The syntax: getline(cin, variable name);
Example:

#include <iostream.h>
#include <cstring>
using namespace std;
main ()
{
string name;
cout << "Enter your name: ";
getline(cin, name);
cout << "Welcome " << name << "!"; Output :
Enter your name: hasrinafasya
system(“pause”); Welcome hasrinafasya!
} No. of character displayed = length - 1
• Use string predefined functions (string) and must be included in the preprocessor
directive command. → eg: #include <string>
• String input statement
The syntax: cin.getline (variable name, length);
Example:

#include <iostream.h>
#include <string.h>
using namespace std;
main ()
{
char name[5];
cout << "Enter your name: ";
cin.getline(name,7);
cout << "Welcome " << name << "!"; Output :
Enter your name: hasrinafasya
system(“pause”); Welcome hasrin!
} No. of character displayed = length - 1
• Most commonly used string functions (CANNOT be used for cstring):

Manipulators Action
strcpy( ) ▪ To copy a string into another string variable.
▪ Syntax: strcpy(destination array, source array);
strcmp( ) ▪ To compare between two string variables
▪ Syntax: strcmp(s1, s2);
▪ If s1 = s2 then return value is 0
strlen() ▪ Will return the length of string variable
▪ Syntax: strlen(string variable);
strcat() ▪ Will concatenate two string variables
together.
▪ Syntax: strcat(s1, s2);
#include <iostream.h> Output :
#include <string> Enter your name: fasya
using namespace std; My name is fasya
Enter other name: tasya
Difference of ASCII:
main () -14
102 -116 = -14
{ Length of my name is: 5
char userName[20], myName[20], otherName[20], mixName[20]; Combination of two names is: fasyatasya
cout << "Enter your name: ";
cin.getline(userName,20);

strcpy(myName, userName);
cout << "My name is: " << myName << endl;

cout << "Enter other name: ";


cin.getline(otherName, 20);
cout << strcmp(myName, otherName) << endl;

int lengthName;
lengthName = strlen(myName);
cout << "Length of my name is: " << lengthName << endl;

strcpy(mixName, strcat(myName, otherName));


cout << "Combination of two names is: " << mixName << endl;

system(“pause”);
}
• It is used to assign a value to a variable. First, evaluates the expression
on the right and then stores
• Syntax: that value in a memory
location (identifier) on the left.
identifier = expression;

must be a variable can be constant, variable or any complex expression

• The assignment operator used is equal sign (=).


• For example:
Suppose you have the following variable declarations:
int i;
double sale;
char first;
char weather[30];
Now, consider the following assignment statements:
i = 4 * 5 -11;
sale = 0.02 * 1000;
first = ‘A’;
weather = “It is a sunny day.”;
1 line comment // This is a simple C++ program
/* Purpose is to demonstrate the part of
More than1 line
comment a simple C++ program */

Compiler directive
#include <iostream> // necessary for cout and cin
/ preprocessor using namespace std;

main( )
{
int num1, num2, num3, sum;
cout << “This is a Simple C++ Program \n”;
cin >> num1 >> num2 >> num3;
Main function
sum = num1 + num2 + num3;
cout << “The sum of the number is” << sum << endl;
system(“pause”);
}
• Is a combination of operator and operands.
operand operator operand
(Operand → the numbers appearing in the expression)
• Is not a complete statement but it is used in a statement.
• Mainly used to calculate or process data in a program (arithmetic and
logical expression)
• C++ has the following operators:
1. Arithmetic operator
2. Relational operator
3. Logical operator
ARITHMETIC Operation
+ Addition
RELATIONAL Operation ARITHMETIC - Subtraction
< Less than * Multiplication
<= Less than and equal to / Division
> Greater than % Modulus (Remainder)
RELATIONAL
>= Greater than and equal to -- Decrement by 1
== Equal to ++ Increment by 1
!= Not equal to
LOGICAL
LOGICAL Operation
&& AND
|| OR
! NOT
#include <iostream> :
#include <iomanip> int x, y , remainder;
using namespace std; cout << "Enter any two integer numbers: ";
main () cin >> x >> y;
{ remainder = x % y;
int number1, number2, add, sub, mul, inc, dec; cout << "Remainder of division result: " << remainder << endl;

cout << "Enter any two integer numbers: "; inc = ++number1;
cin >> number1 >> number2; cout << "Increment result: " << inc << endl;

add = number1 + number2; dec = --number1;


cout << "Addition result: " << add << endl; cout << "Decrement result: " << dec << endl;

sub = number1 - number2; system(“pause”);


cout << "Subtraction result: " << sub << endl; }
Output :
Enter any two integer numbers: 5 6
mul = number1 * number2;
Addition result: 11
cout << “Multiplication result: " << mul << endl;
Subtraction result: -1
Multiplication result: 30
float div, value1, value2;
Enter any two values: 2 3
cout << "Enter any two values: ";
Division result: 0.67
cin >> value1 >> value2;
Enter any two integer numbers: 3 4
div = value1 / value2;
Remainder of division result: 3
cout << "Division result: " << div << endl;
Increment result: 6
:
Decrement result: 5
Define whether these statements are True or False:
a. int age1=10;
int age2 = 12;
age1<=age2;
True

b. int length = 10;


int width = 10;
length = = width;
True

c. int A = 5;
int B = 10;
int c = 20;

i) (A*B>c/A) || (c<=B) True


ii) (A<B) && (B/A*10>A) True
iii) ((c/B*5)= =5)&&(B/A*10>=c False
• When more than one arithmetic operator is used in an expression, C++ uses the
operator precedence rules to evaluate the expression .
Operator Category Operator
(evaluated from left to right)
Parentheses () Highest

Multiply, Division, Modulus * / %


Add, Subtract + -
Relational Operators < <= > >=
Equality Operators == !=
Logical AND &&
Logical OR || Lowest

The multiplication, division, and modulus operators are evaluated before addition and subtraction
operators. Operators having the same level of precedence are evaluated from left to right.
Grouping is allowed for clarity.
Solve the following C++ expression, given the following values:
If m=5, n=15, p=12

a. n % m + p – p / m = 10
b. (m + n) % n + p = 17
c. n / p + n % p * p = 37
d. (m + n) * (n / m) + (m + p ) – n % 5 * m / m = 77

You might also like