New 5, 6 Data Types of C++1 and Operators With Variables Ab0e5b9d
New 5, 6 Data Types of C++1 and Operators With Variables Ab0e5b9d
Lecture 5
1. Comments:
C++ language can have comments in the body of program, these comments
for explain purpose of program. There are two types of comment in C++
languages:
1. /* C++ program for type my name */.
Example (1):
# include<iostream >
using namespace std;
/* Prints my name, my age, my department, my university */
int main()
{
cout<<" Ahmed.\n"; // my name
cout<<" 18.\n"; // my age
cout<<" Electrical.\n"; // my department
cout<<" Technology.\n"; // my university
}
2. Constants:
Constants refer to fixed values that may not be altered by the program.
They can be of any data type as:
const float pi=3.141;
const float cop-dens = 8.9;
There are three types of constants: string, numeric, and character constants.
1
Department of Electrical Engineering. First Year / 2024-2025 By: Dr.Rasha Subhi Ali
3. Character Constants: Represented by a single character within single quotes (e.g., 'A',
'a'). Maximum size is 8 bits. Special characters are represented using a backslash (\).
3. Data Types:
There are five atomic data types in the C++: character, integer, floating-
point, double floating-point, and valueless. Values of type char are used to
hold ASCII characters or any 8-bit quantity. Variables of type int are used to
hold integer quantities. Variables of type float and double hold real numbers.
(Real numbers have both an integer and a fractional component).
Data type: A type of the data to be stored inside the memory.
Or
Data type: refer to an extensive system used for declaring variables or
functions of different types. C++ data types fall into the following three
categories and are illustrated in figure 2:
1. Simple data type
2. Structured data type
3. Pointers
2
Department of Electrical Engineering. First Year / 2024-2025 By: Dr.Rasha Subhi Ali
3. char
The data type char (takes 1 byte) is the smallest integral data type. It is
mainly used to represent characters—that is, letters, digits, and special
symbols. Thus, the char data type can represent every key on your keyboard.
When using the char data type, you enclose each character represented within
single quotation marks. Examples of values belonging to the char data type
include the following:
'A', 'a', '0', '*', '+', '$', '&', ' '
Note that a blank space is a character and is written as ' ', with a space
between the single quotation marks.
4. float
The data type float is used in C++ to represent any real number between -
3.4E+38 and 3.4E+38. The memory allocated for a value of the float data
type is four bytes.
5. double
The data type double is used in C++ to represent any real number between -
1.7E+308 and 1.7E+308. The memory allocated for a value of the double
data type is eight bytes.
String Type
A string is a sequence of zero or more characters. Strings in C++ are enclosed in double
quotation marks. A string containing no characters is called a null or empty string. The
following are examples of strings. Note that " " is the empty string.
"Mohammed Ali"
"Welcome to C++"
""
Every character in a string has a relative position in the string. The position of the first
character is 0, the position of the second character is 1, and so on. The length of a string is
the number of characters in it
2) Structured Data Types (will be explain later).
3) Pointers (will be explain later).
3
Department of Electrical Engineering. First Year / 2024-2025 By: Dr.Rasha Subhi Ali
Types of Modifiers:
The basic data types may have various modifiers preceding them. A type modifier is
used to alter the meaning of the base type to fit the needs of various situations more
precisely. The list of modifiers is shown here:
signed
unsigned
long short
The modifiers signed, unsigned, long, and short can be applied to integer base types.
The character base type can be modified by unsigned and signed. You can also apply long
to double. Access Modifiers that is used to control the ways in which variables may be
accessed or modified. This modifier is called const variable of type const may not be
changed during execution by your program.
Limits of Modifiers:
C++ program using sizeof() function to find the limits of modifiers, with standard
function limits:
Example (2):
#include<iostream >
# include <limits.h> // The # include <limits.h> can also be written as # include <limits>//
using namespace std;
int main()
{
cout<<sizeof (int)<< "\n" ;
cout<<sizeof (char)<<"\n" ;
cout<<sizeof (float)<<"\n" ;
cout<<sizeof (long double)<<"\n" cout<<sizeof (unsigned short int)<<"\n" ;
}
4
Department of Electrical Engineering. First Year / 2024-2025 By: Dr.Rasha Subhi Ali
Identifier Names:
The names that are used to reference variables, functions, labels, and various other user
defined objects are called identifiers. Identifiers can vary from one to several characters in
length. An identifier in C++ is a sequence of letters, digits, and underscores. An identifier
cannot begin with a digit. Uppercase and lowercase letters are treated as distinct. It is good
practice to choose meaningful names as identifiers. One- or two-letter identifiers can be
used when it is obvious what the name is being used for.
Example (3): determine the types of the words in C++ language:
Float, float, 1float, test23, hit!it, Beta, βeta, 5q,
Ans:
Question: are there the same identifiers: Count, COUNT, and count?
Declaration of Variables:
A variable is a named location in memory that is used to hold a value that can be
modified by the program. All variables must be declared before they are used. The general
form of a declaration is shown here:
type variable list;
Variable list may consist of one or more identifier names with comma separators. Some
declarations are shown here:
int i,j,k;
char h = 'a';
short int si;
unsigned int ahmed;
double balance, loss;
Question: write the instruction to declaring about:
i- integer x and y
ii- floating point -1.233432345
iii- character g,h
There are three basic places where variables can be declared:
Inside functions, in the definition of function parameters, or outside all functions. These
variables are called local variables, formal parameters, and global variables, respectively.
Variables
We might want to give a value a name so we can refer to it later. We do this using
variables. A variable is a named location in memory.
8 return 0;
}
(Note how we can print a sequence of values by “chaining” the << symbol.)
The name of a variable is an identifier token. Identifiers may contain numbers, letters, and
underscores(_), and may not start with a number.
Line 5 is the declaration of the variable x. We must tell the compiler what type x will be so that
it knows how much memory to reserve for it and what kinds of operations may be performed on
it.
Line 6 is the initialization of x, where we specify an initial value for it. This introduces a new
operator: =, the assignment operator. We can also change the value of x later on in the code
using this operator.
We could replace lines 5 and 6 with a single statement that does both declaration and
initialization:
int x = 4 + 2;
This form of declaration/initialization is cleaner, so it is to be preferred.
Ex:
double amountDue;
int counter;
char ch;
int x, y;
string name;
6
Department of Electrical Engineering. First Year / 2024-2025 By: Dr.Rasha Subhi Ali
Notes:
• This statement is valid in C++: num = num + 2; means ‘‘evaluate whatever is in num, add 2 to
it, and assign the new value to the memory location num.’’ The expression on the right side must
be evaluated first; that value is then assigned to the memory location specified by the variable on
the left side. Thus, the sequence of C++ statements:
num = 6;
num = num + 2;
and the statement:
num = 8;
• Suppose that x, y, and z are int variables. The following is a legal statement in C++:
x = y = z;
In this statement, first the value of z is assigned to y, and then the new value of y is assigned to x.
Input (Read) Statement
We can accept multiple values from the standard input by separating them with multiple >>
operators:
This is called an input (read) statement. In C++, >> is called the stream extraction operator.
// This program illustrates how input statements work.
7
Department of Electrical Engineering. First Year / 2024-2025 By: Dr.Rasha Subhi Ali
Justas cout<< is the syntax for outputting values, cin >> (line6) is the syntax for inputting values.
Memory trick: if you have trouble remembering which way the angle brackets go for cout and cin, think
of them as arrows pointing in the direction of data flow. cin represents the terminal, with data flowing
from it to your variables; cout likewise represents the terminal, and your data flows to it.
Example: Suppose you have the following variable declarations:
int a;
double z;
char ch;
Figure 4: Example
Operator types:
1- Assignment Operator
The assignment operator = assigns a value to a variable / object:
Variable= variable operator expression;
Ex: x=x+5;
y=y*10;
The operational assignment operator can be written in the following form:
Ex: x+=5;
Variable operator = expression
y*= 10;
8
Department of Electrical Engineering. First Year / 2024-2025 By: Dr.Rasha Subhi Ali
# include<iostream >
using namespace std;
Figure 7: Example
9
Department of Electrical Engineering. First Year / 2024-2025 By: Dr.Rasha Subhi Ali
V=12/4=3
2- Mathematical (Arithmetic):
Example
# include<iostream >
The integer division, in our example, results in a value of 0. It is because the result of the
integer division where both operands are integers is truncated towards zeros. In the
expression x / y, x and y are operands and / is the operator.
If we want a floating-point result, we need to use the type double and make sure at least
one of the division operands is also of type double:
# include<iostream >
3- Relational Operators:
In the term relational operator the word relational refers to the relationships values can
have with one another. The key to the concepts of relational operators is the idea of true and
false. In C++, true is any value other than 0. False is 0. Expressions that use relational
operators will return 0 for false and 1 for true.
Example (5):
Write a program in C++ language to test the operation of RelationalOperators with printing
11
Department of Electrical Engineering. First Year / 2024-2025 By: Dr.Rasha Subhi Ali
12
Department of Electrical Engineering. First Year / 2024-2025 By: Dr.Rasha Subhi Ali
Example 1: a=4,b=5,c=6
13
Department of Electrical Engineering. First Year / 2024-2025 By: Dr.Rasha Subhi Ali
(((3 * 7) – 6) + ((2 * 5) / 4 )) + 6
= ((21 – 6) + (10 / 4)) + 6 (Evaluate *)
= ((21 – 6) + 2) + 6 (Evaluate /. Note that this is an integer division.)
= (15 + 2) + 6 (Evaluate –)
= 17 + 6 (Evaluate first +)
= 23 (Evaluate +)
Note: Because the char data type is also an integral data type, C++ allows you to perform
arithmetic operations on char data. However, you should use this ability carefully. There is a
difference between the character '8' and the integer 8. The integer value of 8 is 8. The integer
value of '8' is 56, which is the ASCII collating sequence of the character '8'.
When evaluating arithmetic expressions, 8 + 7 = 15;
'8' + '7' = 56 + 55, which yields 111;
'8' + 7 = 56 + 7, which yields 63
14
Department of Electrical Engineering. First Year / 2024-2025 By: Dr.Rasha Subhi Ali
Also,
Both pre-increment and post-increment operators add 1 to the value of our object, and
both pre-decrement and post-decrement operators subtract one from the value of our
object. The difference between the two, apart from the implementation mechanism (very
broadly speaking), is that with the pre-increment operator, a value of 1 is added first. Then
the object is evaluated/accessed in expression. With the post-increment, the object is
evaluated/accessed first, and after that, the value of 1 is added. To the next statement that
follows, it does not make a difference. The value of the object is the same, no matter what
version of the operator was used. The only difference is the timing in the expression where it
is used.
However, there is a difference when they are used in an expression. When an increment or
decrement operator precedes its operand, C++ performs the increment or decrement
operation prior to obtaining the operand’s value.
Example (3):
Write a program in C|++ language to test the operation of arithmeticoperators with printing the result
appearing on the screen of computer.
Ans:
#include<iostream>
15
Department of Electrical Engineering. First Year / 2024-2025 By: Dr.Rasha Subhi Ali
What is the difference between the pre and post forms of these operators?
The difference becomes apparent when the variable using these operators is employed
in an expression.
Suppose that x is an int variable. If ++x is used in an expression, first the value of x is
incremented by 1, and then the new value of x is used to evaluate the expression. On the
other hand, if x++ is used in an expression, first the current value of x is used in the
expression, and then the value of x is incremented by 1. The following example clarifies
the difference between the pre- and post-increment operators.
Suppose that x and y are int variables. Consider the following statements:
16
Department of Electrical Engineering. First Year / 2024-2025 By: Dr.Rasha Subhi Ali
x = 5;
y = ++x;
The first statement assigns the value 5 to x. To evaluate the second statement, which
uses the pre-increment operator, first the value of x is incremented to 6, and then this value,
6, is assigned to y. After the second statement executes, both x and y have the value 6.
Now, consider the following statements:
x = 5;
y = x++;
As before, the first statement assigns 5 to x. In the second statement, the postincrement
operator is applied to x. To execute the second statement, first the value of x, which is 5, is
used to evaluate the expression, and then the value of x is incremented to 6. Finally, the
value of the expression, which is 5, is stored in y. After the second statement executes, the
value of x is 6, and the value of y is 5.
Example: Suppose a and b are int variables and:
a = 5;
b = 2 + (++a);
The first statement assigns 5 to a. To execute the second statement, first the expression
2 +(++a) is evaluated. Because the pre-increment operator is applied to a, first the value of
a is incremented to 6. Then 2 is added to 6 to get 8, which is then assigned to b.
Therefore, after the second statement executes, a is 6 and b is 8.
On the other hand, after the execution of the following statements:
a = 5;
b = 2 + (a++);
The value of a is 6 while the value of b is 7.
Question: What is the difference between ++a and a++. Question: find the
result of the following if int n=7, m=24;1. 37/(5%3)
2. m-8-n
3. m%n++
4. ++m-n
5. m*=n++6. m+=--n
The following program reads three different inputs and outputs it. #include void
main()
{
int num=3;
cout << "number="<<num<<"\n";
char ch='a';
cout << "character="<<ch<<"\n"; f
float fa=-34.45;
cout<<"real number="<<fa<<"\ n";
The following program reads three different inputs and outputs it. #include void
main() { } int n; float f; char c; cout << "input integer number:"; cin>>n;
17
Department of Electrical Engineering. First Year / 2024-2025 By: Dr.Rasha Subhi Ali
18
Department of Electrical Engineering. First Year / 2024-2025 By: Dr.Rasha Subhi Ali
Instead of writing a large and complex code, you can create your own header files and include it in
the C/C++ library to use it whenever you wish as frequently as you like. It enhances code
functionality and readability.
Let us understand how to create your own header file in C++ with the help of an example.
Consider a problem where you want to compute the factorial of a number. Since it not pre-defined
in the standard C++ library, you can create it by yourself!
The Steps involved are:
Step – 1
Write your own code in C++ and save the file with a .h extension instead of a .cpp, because you
are creating a header file, not a C++ program. The name of the file you save with .h
extension would be the name of your header file. Suppose you named it factorial.h.
int factorial(int number)
{
int iteration, factorial=1;
for(iteration=1; iteration<=number; iteration++)
{
factorial=factorial*iteration;
}
return factorial;
}
Step – 2
Open a fresh window and include your header file. In this case, you can write in two ways:
#include“factorial.h” – Enclosing the header file name within double quotes signifies that the
header file of C and C++ is located in the present folder you are working with. It is a preferred
practice to include user-defined header files in this manner.
#include<factorial.h> – Enclosing the header file name within angular brackets signifies that
the header file is located in the standard folder of all other header files of C/C++.
Step – 3
After the code is written using your file with the .h extension, compile and run your
program. This is a C++ program to find the factorial of a number using a self-created
header file:
#include <iostream>
#include"factorial.h"
using namespace std;
int main()
{
cout<<"Welcome to DataFlair tutorials!"<<"\n"<<"\n";
int positive_integer;
cout<<"Enter a positive integer: "<<"\n";
cin>>positive_integer;
cout<<"The factorial of " << positive_integer << " is: " << factorial(positive_integer) <<"\n";
return 0;
}
Output-
Used to perform input and output operations in C like scanf() and printf().
2. #include<string.h> (String header)
Perform string manipulation operations like strlen and strcpy.
3. #include<conio.h> (Console input-output header)
Perform console input and console output operations like clrscr() to clear the screen and getch()
to get the character from the keyboard.
4. #include<stdlib.h> (Standard library header)
Perform standard utility functions like dynamic memory allocation, using functions such as
malloc() and calloc().
5. #include<math.h> (Math header )
Perform mathematical operations like sqrt() and pow(). To obtain the square root and the power
of a number respectively.
6. #include<ctype.h>(Character type header)
Perform character type functions like isaplha() and isdigit(). To find whether the given character
is an alphabet or a digit respectively.
7. #include<time.h>(Time header)
Perform functions related to date and time like setdate() and getdate(). To modify the system
date and get the CPU time respectively.
8. #include<assert.h> (Assertion header)
It is used in program assertion functions like assert(). To get an integer data type in C/C++ as a
parameter which prints stderr only if the parameter passed is 0.
9. #include<locale.h> (Localization header)
Perform localization functions like setlocale() and localeconv(). To set locale and get locale
conventions respectively.
10. #include<signal.h> (Signal header)
Perform signal handling functions like signal() and raise(). To install signal handler and to raise
the signal in the program respectively
11. #include<setjmp.h> (Jump header)
Perform jump functions.
12. #include<stdarg.h> (Standard argument header)
Perform standard argument functions like va_start and va_arg(). To indicate start of the
variable-length argument list and to fetch the arguments from the variable-length argument list
in the program respectively.
13. #include<errno.h> (Error handling header)
Used to perform error handling operations like errno(). To indicate errors in the program by
initially assigning the value of this function to 0 and then later changing it to indicate errors.
20