CSC201 Lect3
CSC201 Lect3
Output Operator - the statement cout <<” ”; is used to display information on the
screen. The cout can be used to display individual characters, strings and even numbers.
It is a predefined object that corresponds to the standard output stream. Stream just
refers to a flow of data and the standard Output stream normally flows to the screen
display. The cout object, whose properties are defined in iostream.h represents that
stream. The operator “<<” is called ‘insertion’ or ‘put to’ operator and it directs the
information on its right to the object on its left.
Input Operator - the statement “cin>> values;” is used to accept user input statement
to the program. The identifier cin is a predefined object in C++ that corresponds to the
standard input stream. Here, this stream represents the keyboard. The operator “>>” is
called ‘extractor’ or ‘get from’ operator. It extracts value from the keyboard and assigns
it to the variable on its right.
Return Statement - In C++, main ( ) returns an integer type value to the operating
system. Therefore every main ( ) in C++ should end with a return (0) statement,
otherwise a warning or an error might occur.
Tokens – is the smallest individual units in program. C++ has the following tokens.
o Keywords
o Identifiers
o Constants
o Strings
o Operators
Keywords - implement specific C++ language feature. They are explicitly reserved
identifiers and can’t be used as names for the program variables or other user defined
program elements. The keywords in C++ are:
Asm, double, new, switch, Auto, else, operator, template, Break, enum, private, this,
Case, extern, protected, throw, Catch, float, public, try, Char, for, register, typedef,
Class, friend, return, union, Const, goto, short, unsigned, Continue, if, signed, virtual,
Default, inline, sizeof, void, Delete, long, struet, while.
Identifiers - refers to the name of variable, functions, array, class etc. created by
programmer. Each language has its own rule for naming the identifiers. C++ identifier
rules:
Only alphabetic chars, digits and underscores are permitted.
The name can’t start with a digit.
Upper case and lower-case letters are distinct.
A declared keyword can’t be used as a variable name.
Comments – comments are explanations for human readers of your code. The compiler
does not execute or process comments. As your program progresses and gets more
complex, there is need to explain the steps in the program.
Two types of comments:
o Single line comments, denoted with the syntax //
o Multi line comments, denoted with the syntax /* and */
For example:
float scalerate = 9.0/5.0; // measures the degrees of Celsius and Fahrenheit readings.
o This comment explains the significance of the value 9.0/5.0 to a human reader.
o a comment that spans multiple lines, enclose it between /* and */. Example:
/*
This program computes the Fahrenheit in degrees from the input generated from the
Celsius readings. */
VARIABLES AND DATA TYPES
When your program carries out computations, you will want to store values so that you
can use them later. In a C++ program, you use variables to store values.
A variable is a storage location in a computer program. Each variable has a name and
holds a value.
A variable is a name which is associated with a value that can be changed.
For example, when we write: int age =20;
the variable name is “age” which is associated with value 20, int is a data type that
represents that this variable can hold integer values.
Syntax of declaring a variable in C++
data_type variable1_name = value1, variable2_name = value2;
For example:
int age = 20, phonenum = 090112233;
We can also write it like this:
int age, phonenum; // this means declaring the variables age and phonenum.
age=20; // this means assigning values to age.
phonenum= 090112233; // assigning values to phonenum.
When declaring a variable, we can initialize it. That is, we specify the value that should
be stored in the variable. Example:
int my_number = 3;
The variable my_number is initialized with the value 3.
Variable names
When we define a variable, we pick a name that explains its purpose. For example, it is
better to use a descriptive name, such as student_age than a terse name, such as sa.
In C++, there are a few simple rules for variable names:
o Variable names must start with a letter or the underscore (_) character, and the
remaining characters must be letters, numbers, or underscores.
o You cannot use other symbols such as $ or %. Spaces are not permitted inside
names either. You can use an underscore instead, as in student_age.
o Variable names are case-sensitive, that is, Student_age and student_age are
different names. For that reason, it is a good idea to use only lowercase letters in
variable names.
o You cannot use reserved words such as double or return as names; these words
are reserved exclusively for their special C++ meanings.
Types of variables
Variables can be categorised based on their data type. For example, in the above
example we have seen integer types variables. Following are the types of variables
available in C++.
int: This type of variable holds integer values.
char: holds character value like ‘c’, ‘F’, ‘B’, ‘p’, ‘q’ etc.
bool: holds Boolean value like true or false.
double: holds double-precision floating point value.
float: holds single-precision floating point value.
Global Variable - a variable declared outside of any function (including main as well)
is called global variable. Global variables have their scope throughout the program, and
can be accessed anywhere in the program.
Example:
o the global variable gloVar is declared outside of main. We will access the
variable twice in the main() function without any issues.
#include <iostream>
using namespace std;
char gloVar = '9'; // This is a global variable
int main()
{
cout <<"Value of Global variable1: "<< gloVar<<endl;
gloVar = 'A';
cout <<"Value of Global variable2: "<< gloVar;
return 0;
}
Output:
Value of Global variable1: 9
Value of Global variable2: A
Local variable – is declared inside the braces of any user defined function, main
function, loops or any control statements(if, if-else etc) and have their scope limited
inside those braces.
Example:
#include <iostream>
using namespace std;
int main()
{
char locVar = 'A';
cout <<"Value of Local Variable: "<< locVar<<endl;
return 0;
}
Output:
Value of Local variable: A
Constants
When a variable is declared with the reserved word const, its value can never change.
so, any value declared as const can’t be modified by the program in any way.
Example:
const int size = 4;
It is good programming style to use named constants in your program to explain the
meanings of numeric values. For example, compare the statements
double total_volume = length * 4;
and
double total_volume = length * size;
A programmer reading the first statement may not understand the significance of the
number 4. The second statement, with a named constant, makes the computation much
clearer.
DATA TYPES
Data types define the type of data a variable can hold. For example, an integer variable
can hold integer data, and a character type variable can hold character data etc.
Data types in C++ are categorised in three groups: Built-in, User-defined and Derived.
Operators in C++
Operator represents an action. For example, + is an operator that represents addition.
An operator works on two or more operands and produce an output.
Types of Operators in C++:
o Basic Arithmetic Operators
o Assignment Operators
o Auto-increment and Auto-decrement Operators
o Logical Operators
o Comparison (relational) operators
o Bitwise Operators
o Ternary Operator
#include <iostream>
using namespace std;
int main(){
int num1 = 140;
int num2 = 40;
cout<<"num1 + num2: "<<(num1 + num2)<<endl;
cout<<"num1 - num2: "<<(num1 - num2)<<endl;
cout<<"num1 * num2: "<<(num1 * num2)<<endl;
cout<<"num1 / num2: "<<(num1 / num2)<<endl;
cout<<"num1 % num2: "<<(num1 % num2)<<endl;
return 0;
}
Output:
num1 + num2: 180
num1 - num2: 100
num1 * num2: 5600
num1 / num2: 3
num1 % num2: 20
Assignment Operators
Assignments operators in C++ are: =, +=, -=, *=, /=, %=
num2 = num1 would assign value of variable num1 to the variable num2.
num2 += num1 is equal to num2 = num2 + num1
num2 -= num1 is equal to num2 = num2 - num1
num2 *= num1 is equal to num2 = num2 * num1
num2 /= num1 is equal to num2 = num2 / num1
num2 %= num1 is equal to num2 = num2 % num1
Example of Assignment Operators
#include <iostream>
using namespace std;
int main(){
int num1 = 240;
int num2 = 40;
num2 = num1;
cout<<"= Output: "<<num2<<endl;
num2 += num1;
cout<<"+= Output: "<<num2<<endl;
num2 -= num1;
cout<<"-= Output: "<<num2<<endl;
num2 *= num1;
cout<<"*= Output: "<<num2<<endl;
num2 /= num1;
cout<<"/= Output: "<<num2<<endl;
num2 %= num1;
cout<<"%= Output: "<<num2<<endl;
return 0;
}
Output:
= Output: 40
+= Output: 180
-= Output: 40
*= Output: 5600
/= Output: 40
%= Output: 40
Logical Operators
Logical Operators are used with binary variables. They are mainly used in conditional
statements and loops for evaluating a condition.
Logical operators in C++ are: &&, ||, !
Let’s say we have two Boolean variables b1 and b2.
b1 && b2 will return true if both b1 and b2 are true else it would return false.
b1 || b2 will return false if both b1 and b2 are false else it would return true.
!b1 would return the opposite of b1, that means it would be true if b1 is false and
it would return false if b1 is true.
#include <iostream>
using namespace std;
int main(){
bool b1 = true;
bool b2 = false;
cout<<"b1 && b2: "<<(b1&&b2)<<endl;
cout<<"b1 || b2: "<<(b1||b2)<<endl;
cout<<"!(b1 && b2): "<<!(b1&&b2);
return 0;
}
Output:
b1 && b2: 0
b1 || b2: 1
!(b1 && b2): 1
Relational operators
We have six relational operators in C++: ==, !=, >, <, >=, <=
o == returns true if both the left side and right side are equal
o != returns true if left side is not equal to the right side of operator.
o > returns true if left side is greater than right.
o < returns true if left side is less than right side.
o >= returns true if left side is greater than or equal to right side.
o <= returns true if left side is less than or equal to right side.
Example of Relational operators
#include <iostream>
using namespace std;
int main(){
int num1 = 140;
int num2 =40;
if (num1==num2) {
cout<<"num1 and num2 are equal"<<endl;
}
else{
cout<<"num1 and num2 are not equal"<<endl;
}
if(num1 != num2 ){
cout<<"num1 and num2 are not equal"<<endl;
}
else{
cout<<"num1 and num2 are equal"<<endl;
}
if(num1 > num2 ){
cout<<"num1 is greater than num2"<<endl;
}
else{
cout<<"num1 is not greater than num2"<<endl;
}
if(num1 >= num2 ){
cout<<"num1 is greater than or equal to num2"<<endl;
}
else{
cout<<"num1 is less than num2"<<endl;
}
if(num1 < num2 ){
cout<<"num1 is less than num2"<<endl;
}
else{
cout<<"num1 is not less than num2"<<endl;
}
if(num1 <= num2){
cout<<"num1 is less than or equal to num2"<<endl;
}
else{
cout<<"num1 is greater than num2"<<endl;
}
return 0;
}
Bitwise Operators
Bitwise operator performs bit by bit processing.
There are six bitwise Operators: &, |, ^, ~, <<, >>
Example:
num1 = 11; /* equal to 00001011*/
num2 = 22; /* equal to 00010110 */
o & - Bitwise AND operator - if we have num1 & num2, compares
corresponding bits of num1 and num2 and generates 1 if both bits are equal,
else it returns 0. In our case it would return: 2 which is 00000010 because in the
binary form of num1 and num2 only second last bits are matching.
o | - Bitwise OR Operator - num1 | num2 compares corresponding bits of num1
and num2 and generates 1 if either bit is 1, else it returns 0. In our case it would
return 31 which is 00011111
o ^ - Bitwise XOR operator. num1 ^ num2 compares corresponding bits of num1
and num2 and generates 1 if they are not equal, else it returns 0. In our example
it would return 29 which is equivalent to 00011101
o ~ - Bitwise Complement operator - num1 is a complement operator that just
changes the bit from 0 to 1 and 1 to 0. In our example it would return -12 which
is signed 8 bit equivalent to 11110100
o << - Bitwise Shift Left operator - num1 << 2 is left shift operator that moves
the bits to the left, discards the far left bit, and assigns the rightmost bit a value
of 0. In our case output is 44 which is equivalent to 00101100
o >> - Bitwise Shift Right operator - num1 >> 2 is right shift operator that moves
the bits to the right, discards the far right bit, and assigns the leftmost bit a value
of 0. In our case output is 2 which is equivalent to 00000010
#include <iostream>
using namespace std;
int main(){
int num1 = 11; /* 11 = 00001011 */
int num2 = 22; /* 22 = 00010110 */
int result = 0;
result = num1 & num2;
cout<<"num1 & num2: "<<result<<endl;
result = num1 | num2;
cout<<"num1 | num2: "<<result<<endl;
result = num1 ^ num2;
cout<<"num1 ^ num2: "<<result<<endl;
result = ~num1;
cout<<"~num1: "<<result<<endl;
result = num1 << 2;
cout<<"num1 << 2: "<<result<<endl;
result = num1 >> 2;
cout<<"num1 >> 2: "<<result;
return 0;
}
Output:
num1 & num2: 2
num1 | num2: 31
num1 ^ num2: 29
~num1: -12
num1 << 2: 44
num1 >> 2: 2
Ternary Operator
This operator evaluates a Boolean expression and assign the value based on the result.
Syntax:
variable num1 = (expression) ? value if true : value if false
If the expression results true then the first value before the colon (:) is assigned to the
variable num1 else the second value is assigned to the num1.
#include <iostream>
using namespace std;
int main(){
int num1, num2; num1 = 99;
/* num1 is not equal to 10 that's why
* the second value after colon is assigned
* to the variable num2
*/
num2 = (num1 == 10) ? 100: 200;
cout<<"num2: "<<num2<<endl;
/* num1 is equal to 99 that's why
* the first value is assigned
* to the variable num2
*/
num2 = (num1 == 99) ? 100: 200;
cout<<"num2: "<<num2;
return 0;
}
Output:
num2: 200
num2: 100
Miscellaneous Operators
There are few other operators in C++ such as Comma operator and sizeof operator.
Comma operator ( , )
The comma operator (,) is used to separate two or more expressions that are included
where only one expression is expected.
When the set of expressions has to be evaluated for a value, only the rightmost
expression is considered. For example, the following code:
a = (b=3, b+2);
o Would first assign the value 3 to b, and then assign b+2 to variable a. So, at the end,
variable a would contain the value 5 while variable b would contain value 3.
sizeof()
This operator accepts one parameter, which can be either a type or a variable itself and
returns the size in bytes of that type or object:
a = sizeof (char);
o This will assign the value 1 to a because char is a one-byte long type. The value
returned by sizeof is a constant, so it is always determined before program
execution.
#include <iostream>
using namespace std;
int main()
{
double price = 2.23;
int naira = price + .5;
cout<<"the price is"<< naira;
return 0;
}
ARITHMETIC EXPRESSIONS
MATHEMATICAL EXPRESSION C++ EXPRESSION COMMENTS
The parentheses are required; x + y / 2
+ (x + y) / 2 .
2
Parentheses are not required;
2 x*y/2 operators with
the same precedence are evaluated left
to right.
b * (1 + )n b * pow(1 + r/100, n) Remember to add #include <cmath>
to the top
of your program.
+ sqrt(a * a + b * b) a * a is simpler than pow(a, 2).
+ + If i, j, and k are integers, using a
3 (i + j + k) / 3.0 denominator
of 3.0 forces floating-point division.