Algorithms and Programming C/C++ 2
Data Types
In programming languages, a data type is a category that defines the type of data being represented. Each piece of data has a different data type, such as numeric data, character data, and others. The common data types in programming are known as primitive data types (meaning they are the most frequently encountered types in programming and are also the oldest types available today). C/C++ is a pioneering programming language for primitive data types and has inspired the creation of other programming languages. Here are the basic data types that can be used in C:
- Boolean: A logical data type that contains Boolean expressions (True/1 and False/0).
- Integer: A data type that holds whole numbers.
- Floating Point: A data type that holds decimal numbers.
- String: A data type that holds characters.
- List/Array: A data type that contains a collection of data with multiple entries. An array can only contain a list of data of the same type.
Numbers & Digits
C/C++ recognizes several types of numbers, including integers and floating-point numbers. Integer and floating-point data types can be further divided into several new types based on the range of values they can hold.
Integer Data Types in C/C++:
Character (can hold integer values)
char has a storage size of 1 byte (8 bits), allowing it to store values in the range of -128 to 127 or 0 to 255.
Short
short has a storage size of 2 bytes (16 bits), allowing it to store values in the range of -32,768 to 32,767 or 0 to 65,535.
Long
long has a storage size of 4 bytes (32 bits), allowing it to store values in the range of -2,147,483,648 to 2,147,483,647 or 0 to 4,294,967,295.
Integer
Integer same as long, Integer has a storage size of 4 bytes (32 bits), allowing it to store values in the range of -2,147,483,648 to 2,147,483,647 or 0 to 4,294,967,295.
Long Long
long long has a storage size of 8 bytes (64 bits), allowing it to store values in the range of -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 or 0 to 18,446,744,073,709,551,615.
Floating Point Data Types in C/C++:
Float
float has a storage size of 4 bytes (32 bits), allowing it to store values in the range of 1.2E-38 to 3.4E+38.
Double
double has a storage size of 8 bytes (64 bits), allowing it to store values in the range of 2.3E-308 to 1.7E+308.
Long Double
long double has a storage size of 10 bytes (80 bits), allowing it to store values in the range of 3.4E-4932 to 1.1E+4932.
Numeric data types also have categorization for storing positive and negative numbers. This categorization is known as signed and unsigned.
Unsigned
unsigned is a data type that can only store positive values. It can be used with char, short, long, and long long.
Signed
signed is a data type that can store both positive and negative values. It can also be used with char, short, long, and long long.
Here’s an example of applying numeric data types in C/C++:
Source Code:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using namespace std;
int main() {
unsigned char variable_char = 255;
signed short variable_short = 32767;
int variable_int = 2147483647;
float variable_float = 10.5;
double variable_double = 23230204.5;
printf("%d\n", variable_char);
printf("%d\n", variable_short);
printf("%d\n", variable_int);
printf("%g\n", variable_float);
printf("%g\n", variable_double);
return 0;
}
Output:1
2
3
4
5255
32767
2147483647
10.5
2.32302e+07
Boolean Expressions
A Boolean expression is an expression that returns a value of True or False, using relational operators/comparison operators, as well as logical operators. Additionally, Boolean expressions can also utilize membership operators and identity operators in certain cases. In C, Boolean values can be represented with 0 as False and 1 as True.
List/Array
A list/array is a collection that contains multiple data items. Generally, lists have an index (an order within the collection of data) that starts from 0. To declare a list, you can add square brackets “[]” after the variable name, followed by curly braces “{}” to declare the list, with each item separated by commas “,”.
Basic Example of Using a List:1
2
3
4
5
6
7
8
9
10
11
12
using namespace std;
int main() {
int thisList[] = {25, 50, 75, 100};
printf("%d", thisList[0]);
printf("%d", thisList[3]);
return 0;
}
String
In C, a string is represented as a list/array of characters (character data type). If you try to execute commands on a variable of string data type, the results will be the same as those produced in a list, as shown in the example below:
1 |
|
Variable
A variable is a place for storing data. If we compare it to something, a variable is like a box. This box has attributes such as the name of the box, notes on the type of contents it holds, and the contents themselves. Therefore, we can conclude that a variable has a name, a type/data type for its contents, and the contents themselves.
In programming languages, variables generally fall into two common types: immutable/constant variables and mutable variables.
To declare a mutable variable in C, you need to write the data type in front of the variable name, followed by assigning a value to the variable using the equals sign (=) as the assignment operator.
Example of Declaring a Mutable Variable in C/C++:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16int int_thisFive = 5;
string str_ThisName = "Your Name";
float flt_thisFivePointSeven = 5.7;
int tf_thisStatus = 0;
```c
For declaring an immutable variable, you should name the variable in all capital letters.
Example of Declaring an Immutable/Constant Variable in C/C++:
```c
const int TRUE = 1;
const int THREE = 3;
Variable data types can also be converted to other data types, but you must ensure compatibility between the original data type and the target data type. For instance, if you want to convert a numeric integer data type to a numeric float data type, this can be done by considering the value range of the original integer type before conversion and the float type you want to convert to.
Be cautious when converting variable data types and always consider the compatibility of data types and the storage space of each type.
Example of Data Type Conversion:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using namespace std;
int main() {
char thisChar = 15;
printf("Number %d is still of char type\n", thisChar);
iniChar = (short) iniChar;
printf("Number %d is now of short type\n", thisChar);
return 0;
}
In addition to the two common types mentioned above, there are also types based on usage. Generally, variable usage is divided into two types: local variables and global variables. A global variable is accessible in any program block, while a local variable can only be accessed within a specific program block, such as in a function or class.
We will discuss examples of global and local variables in the next session.
Operator
Arithmetic Operators
Arithmetic operations are part of number processing in a computer for performing calculations. In addition to performing calculations, arithmetic operations can also be used for logical operations. The foundation of performing calculations in computer arithmetic is addition, also known as the adder.
Here are the Arithmetic Operators in the C/C++ Programming Language.
Operator | Symbol |
---|---|
Addition | + |
Substraction | - |
Multiplication | * |
Division | / |
Remainder of Share | % |
This is was example of the Arithmatics Operation:
1 | cout<<3 + 2<<endl; |
Mathematical operators function works normally in C/C++, just like in other programming languages. There are several notes to keep in mind:
- Multiple variables can be assigned the same value in one statement.
- Parentheses () are used to group operations that should be performed first.
- Division of an integer by an integer will round down.
- An integer will be converted to a floating-point number in operations involving both integers and floating-point numbers.
- We cannot convert a complex number to a real number (floating-point or integer); only its absolute value can be obtained.
Assignment Operators
As the name suggests, this operator is used to assign values to variables. For example: age = 18
This means the variable age has been assigned the value of 18. In addition to storing or assigning values, you can also perform addition, subtraction, multiplication, division, etc. More details can be found in the following table.
Operator | Symbol |
---|---|
Filling | = |
Addition | += |
Substraction | -= |
Multiplication | *= |
Division | /= |
Remainder of Share | %= |
The Increment and Decrement operators are operators that can add or subtract 1 from a variable. These operators are often used in loops and arithmetic operations. More details can be seen in the table below.
Operator | Symbol |
---|---|
Increment | ++ |
Decrement | -- |
Comparison Operators
Comparison operators are operators that compare two values. These are also known as relational operators and are often used to create logic or conditions. Below is a list of Comparison Operators in C/C++:
Operator | Symbol |
---|---|
Greater than | > |
Smaller than | < |
Equals to | == |
Not Equals to | != |
Greater than or Equals to | >= |
Smaller than or Equals to | <= |
Logical Operators
Logical operators are operators used to create logic in the programs we write. Logical operators are often referred to as Boolean algebra operators and are typically used to create branching operations in a program. The logical operators include AND, OR, and NOT.
The logical operators consist of:
Operator | Symbol |
---|---|
AND Logic | && |
OR Logic | || |
Negation Logic | ! |
Bitwise Operators
As the name suggests, bitwise operators are used to perform bit-level operations on values in a computer. Here are the bitwise operators available in C/C++:
Operator | Symbol |
---|---|
Bitwise AND | & |
Bitwise OR | | |
Bitwise NOT | ~ |
Bitwise XOR | ^ |
Bitwise Right Shift | >> |
Bitwise Left Shift | << |
Input and Output Functions
Output
The Output function is used to display something, often for showing a value that can be read and seen by the user. Generally, the Output function uses the command print(). Its usage can be seen in the code below:
Code:1
2
3
4
5
6
7
8
9
10
11
using namespace std;
int main() {
printf("This is the Printf Output Function\n");
cout << "This is the C Out Output Function" << endl;
return 0;
}
Output:1
2This is the Printf Output Function
This is the C Out Output Function
What if we want to include variables in the output function? To insert a variable into printf, you need to add a % sign as a data type identifier, whereas with cout, you simply include the variable name.
Here’s an example:
Code:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using namespace std;
int main() {
int x = 5;
string y = "example";
float z = 5.5;
// Just Variables Without String
printf("%d\n", x); // %d is used to insert an integer type into printf like this
printf("%c\n", x); // %c is used to insert a character type into printf like this
printf("%g\n", z); // %g is used to insert a float type into printf like this
printf("%s\n", y.c_str()); // %s is used to insert a string type into printf like this
cout << x << endl;
cout << y << endl;
cout << z << endl;
// Combining String with Variables
printf("this is %d\n", x); // %d is used to insert an integer type into printf like this
cout << "This is " << y << endl;
return 0;
}
Output:1
2
3
4
5
6
7
8
95
5.5
pq�J�
5
example
5.5
this is 5
This is example
Input
The Input function is used to request values from the user and input them into a program. Generally, the Input function uses the scanf() and cin commands. Here’s an example of using input functions in C/C++:
Code:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using namespace std;
int main() {
// Input String
// scanf() cannot be used to input strings
// cin
string x;
cout << "Enter a Free Word: ";
cin >> x;
// Input String with Spaces
// getline for strings with spaces
string c;
cout << "Enter a Free Sentence: ";
cin.ignore(); // to ignore the newline character left in the buffer
getline(cin, c);
// Input Integer
// scanf()
int y;
printf("Enter a Free Number: ");
scanf("%d", &y);
// cin
int z;
cout << "Enter a Free Number: ";
cin >> z;
// Input Decimal Number
// scanf()
float a;
printf("Enter a Free Decimal Number: ");
scanf("%g", &a);
// cin
float b;
cout << "Enter a Free Decimal Number: ";
cin >> b;
cout << x << endl;
cout << y << endl;
cout << z << endl;
cout << a << endl;
cout << b << endl;
cout << c << endl;
return 0;
}
Output:1
2
3
4
5
6
7
8
9
10
11
12Enter a Free Word: test (User Input)
Enter a Free Sentence: I Went to the Market (User Input)
Enter a Free Number: 5 (User Input)
Enter a Free Number: 2 (User Input)
Enter a Free Decimal Number: 2.3 (User Input)
Enter a Free Decimal Number: 2.2 (User Input)
test
5
2
2.3
2.2
I Went to the Market
Package & Library
Packages and Libraries are bundles or groups of many functions and classes (source code) combined into a single unit in the library that can be used and called in the source code you are developing, allowing you to obtain a function without having to repeatedly type the source code. C/C++ provides packages/libraries for standard operations. For more specific operations, you may need to use functions from other packages. In this practical session, we will learn about arithmetic operations and how to use a package to call trigonometric operation functions, which are provided in C/C++’s Math package.
Example of using a Library/Package:1
2
3
4
5
6
7
8
9
10
11
12
13
using namespace std;
int main() {
float flt_root = sqrt(9);
cout<<flt_root<<endl;
return 0;
}