Lecture Note 1A Introduction To C++ 17-10-2024
Lecture Note 1A Introduction To C++ 17-10-2024
int main()
{
cout << "Beginners are always welcome to C++ programming skills!\n";
return 0;
}
Don't worry if you don't understand the code above - we will discuss it in detail in this lecture and other subsequent lectures.
But for now, let us focus on how to run the code.
In Codeblocks, it should look like this:
Then, go to Build > Build and Run to run (execute) the program. The result will look something to this:
Example explained
Line 1: #include <iostream> is a header file library that lets us work with input and output objects, such as cout (used in line
5). Header files add functionality to C++ programs.
Line 2: using namespace std means that we can use names for objects and variables from the standard library. Don't worry if
you don't understand how #include <iostream> and using namespace std works. Just think of it as something that (almost) always
appears at the beginning of your program.
Line 3: A blank line. C++ ignores white space. But we use it to make the code more readable.
Line 4: int main(). This is called a function. Any code inside its curly brackets {} will be executed.
Line 5: cout (pronounced "see-out") is an object used together with the insertion operator (<<) to output/print text. In our
example, it will output " Beginners are always welcome to C++ programming skills!".
Note: C++ is case-sensitive: "cout" and "Cout" have different meaning.
int main() {
cout << " Beginners are always welcome to C++ programming skills!\n";
int main() {
cout << " Beginners are always welcome to C++ programming skills!" << "\n";
cout << "I am learning C++";
return 0;
}
Tip: Two \n characters after each other will create a blank line:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Beginners are always welcome to C++ programming skills!" << "\n\n";
cout << "I am learning C++";
return 0;
}
Another way to insert a new line, is with the endl manipulator:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Beginners are always welcome to C++ programming skills!" << endl;
cout << "I am learning C++";
return 0;
}
Both \n and endl are used to break lines. However, \n is most used.
To create a variable that should store a number, look at the following example:
Example
Create a variable called myNum of type int and assign it the value 15:
int myNum = 15;
cout << myNum;
You can also declare a variable without assigning the value, and assign the value
later:
Example
int myNum;
myNum = 15;
cout << myNum;
Note that if you assign a new value to an existing variable, it will overwrite the
previous value:
Example
int myNum = 15; // myNum is 15
myNum = 10; // Now myNum is 10
cout << myNum; // Outputs 10
Other Types
A demonstration of other data types:
Example
int myNum = 5; // Integer (whole number without decimals)
double myFloatNum = 5.99; // Floating point number (with decimals)
char myLetter = 'D'; // Character
string myText = "Hello"; // String (text)
bool myBoolean = true; // Boolean (true or false)
Display Variables
The cout object is used together with the << operator to display variables.
To combine both text and a variable, separate them with the << operator:
Example
int myAge = 35;
cout << "I am " << myAge << " years old.";
Add Variables Together
To add a variable to another variable, you can use the + operator:
Example
int x = 5;
int y = 6;
int sum = x + y;
cout << sum;
C++ Declare Multiple Variables
Declare Many Variables
To declare more than one variable of the same type, use a comma-separated list:
Example
int x = 5, y = 6, z = 50;
cout << x + y + z;
One Value to Multiple Variables
You can also assign the same value to multiple variables in one line:
Example
int x, y, z;
x = y = z = 50;
cout << x + y + z;
C++ Identifiers
All C++ variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
Note: It is recommended to use descriptive names in order to create understandable and maintainable code:
Example
// Good
int minutesPerHour = 60;
// OK, but not so easy to understand what m actually is
int m = 60;
The general rules for naming variables or identifier are:
i. Names can contain letters, digits and underscores
ii. Names must begin with a letter or an underscore (_)
iii.Names are case-sensitive (myVar and myvar are different variables)
iv.Names cannot contain whitespaces or special characters like !, #, %, etc.
v. Reserved words (like C++ keywords, such as int) cannot be used as names
C++ Constants
Constants
When you do not want others (or yourself) to change existing variable values, use
the const keyword (this will declare the variable as "constant", which means
unchangeable and read-only):
Example
const int myNum = 15; // myNum will always be 15
myNum = 10; // error: assignment of read-only variable 'myNum'
You should always declare the variable as constant when you have values that are unlikely to
change:
Example
const int minutesPerHour = 60;
const float PI = 3.14;
Notes On Constants
When you declare a constant variable, it must be assigned with a value:
Example
const int minutesPerHour = 60;
This however, will not work:
const int minutesPerHour;
minutesPerHour = 60; // error
C++ Variables Examples
Real-Life Examples
Let's get a bit more practical!
Often in our examples, we simplify variable names to match their data type (myInt or myNum for int types, myChar for char
types, and so on). This is done to avoid confusion.
However, for a practical example of using variables, we have created a program that stores different data about a college student:
Example
// Student data
int studentID = 15;
int studentAge = 23;
float studentFee = 75.25;
char studentGrade = 'B';
// Print variables
cout << "Student ID: " << studentID << "\n";
cout << "Student Age: " << studentAge << "\n";
cout << "Student Fee: " << studentFee << "\n";
cout << "Student Grade: " << studentGrade << "\n";
Calculate the Area of a Rectangle
In this real-life example, we create a program to calculate the area of a rectangle (by
multiplying the length and width):
Example
// Create integer variables
int length = 4;
int width = 6;
int area;
// Calculate the area of a rectangle
area = length * width;
// Print the variables
cout << "Length is: " << length << "\n";
cout << "Width is: " << width << "\n";
cout << "Area of the rectangle is: " << area << "\n";
C++ Data Types
As explained in the Variables chapter, a variable in C++ must be
a specified data type:
Example
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
double myDoubleNum = 9.98; // Floating point number
char myLetter = 'D'; // Character
bool myBoolean = true; // Boolean
string myText = "Hello"; // String
Data Type Size Description
boolean 1 byte Stores true or false values
char 1 byte Stores a single character/letter/number, or ASCII values
int 2 or 4 bytes Stores whole numbers, without decimals
Stores fractional numbers, containing one or more decimals. Sufficient
float 4 bytes
for storing 6-7 decimal digits
Stores fractional numbers, containing one or more decimals. Sufficient
double 8 bytes
for storing 15 decimal digits
C++ Numeric Data Types
Numeric Types
Use int when you need to store a whole number without decimals, like 35 or 1000, and float or double when you
need a floating-point number (with decimals), like 9.99 or 3.14515.
int
int myNum = 1000;
cout << myNum;
float
float myNum = 5.75;
cout << myNum;
double
double myNum = 19.99;
cout << myNum;
float vs. double
The precision of a floating point value indicates how many digits the value can
have after the decimal point. The precision of float is only six or seven decimal
digits, while double variables have a precision of about 15 digits. Therefore, it is
safer to use double for most calculations.
Scientific Numbers
A floating point number can also be a scientific number with an "e" to indicate the
power of 10:
Example
float f1 = 35e3;
double d1 = 12E4;
cout << f1;
cout << d1;
C++ Boolean Data Types
Boolean Types
A boolean data type is declared with the bool keyword and can
only take the values true or false.
When the value is returned, true = 1 and false = 0.
Example
bool isCodingFun = true;
bool isFishTasty = false;
cout << isCodingFun; // Outputs 1 (true)
cout << isFishTasty; // Outputs 0 (false)
C++ Character Data Types
Character Types
The char data type is used to store a single character. The character must be surrounded by single
quotes, like 'A' or 'c':
Example
char myGrade = 'B';
cout << myGrade;
Alternatively, if you are familiar with ASCII, you can use ASCII values to display certain
characters:
Example
char a = 65, b = 66, c = 67;
cout << a;
cout << b;
cout << c;
C++ String Data Types
String Types
The string type is used to store a sequence of characters (text). This is not a built-in type, but it behaves like one in
its most basic usage. String values must be surrounded by double quotes:
Example
string greeting = "Hello";
cout << greeting;
Note: To use strings, you must include an additional header file in the source code, the <string> library:
Example
// Include the string library
#include <string>
// Create a string variable
string greeting = "Hello";
// Print variables
cout << "Number of items: " << items << "\n";
cout << "Cost per item: " << cost_per_item << "" << currency << "\n";
cout << "Total cost = " << total_cost << "" << currency << "\n";
C++ Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Example
int x = 100 + 50;
Although the + operator is often used to add together two values, like in the
example above, it can also be used to add together a variable and a value, or a
variable and another variable:
Example
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)
C++ divides the operators into the
following groups:
i.Arithmetic operators
ii.Assignment operators
iii.Comparison operators
iv.Logical operators
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
Operator Name Description Example
+ Addition Adds together two values x+y
- Subtraction Subtracts one value from another x-y
* Multiplication Multiplies two values x*y
/ Division Divides one value by another x/y
% Modulus Returns the division remainder x%y
++ Increment Increases the value of a variable by 1 ++x
-- Decrement Decreases the value of a variable by 1 --x
++ Assignment Operators
Assignment Operators
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) to assign the value 10
to a variable called x:
Example
int x = 10;
The addition assignment operator (+=) adds a value to a variable:
Example
int x = 10;
x += 5;
A list of all assignment operators:
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
ASCII Printable Characters
S/No Char Number Description S/No Char Number Description
Control
1 0-31 51 Q 81 uppercase Q
characters
2 32 space 52 R 82 uppercase R
3 ! 33 exclamation mark 53 S 83 uppercase S
4 " 34 quotation mark 54 T 84 uppercase T
5 # 35 number sign 55 U 85 uppercase U
6 $ 36 dollar sign 56 V 86 uppercase V
7 % 37 percent sign 57 W 87 uppercase W
8 & 38 ampersand 58 X 88 uppercase X
9 ' 39 apostrophe 59 Y 89 uppercase Y
10 ( 40 left parenthesis 60 Z 90 uppercase Z
11 ) 41 right parenthesis 61 [ 91 left square brack
12 * 42 asterisk 62 \ 92 backslash
right square
13 + 43 plus sign 63 ] 93
bracket
14 , 44 comma 64 ^ 94 caret
15 - 45 hyphen 65 _ 95 underscore
16 . 46 period 66 ` 96 grave accent
17 / 47 slash 67 a 97 lowercase a
18 0 48 digit 0 68 b 98 lowercase b
19 1 49 digit 1 69 c 99 lowercase c
20 2 50 digit 2 70 d 100 lowercase d
21 3 51 digit 3 71 e 101 lowercase e
22 4 52 digit 4 72 f 102 lowercase f
23 5 53 digit 5 73 g 103 lowercase g
24 6 54 digit 6 74 h 104 lowercase h
25 7 55 digit 7 75 i 105 lowercase i
26 8 56 digit 8 76 j 106 lowercase j
27 9 57 digit 9 77 k 107 lowercase k
28 : 58 colon 78 l 108 lowercase l
29 ; 59 semicolon 79 m 109 lowercase m
30 < 60 less-than 80 n 110 lowercase n
31 = 61 equals-to 81 o 111 lowercase o
32 > 62 greater-than 82 p 112 lowercase p
33 ? 63 question mark 83 q 113 lowercase q
34 @ 64 at sign 84 r 114 lowercase r
35 A 65 uppercase A 85 s 115 lowercase s
36 B 66 uppercase B 86 t 116 lowercase t
37 C 67 uppercase C 87 u 117 lowercase u
38 D 68 uppercase D 88 v 118 lowercase v
39 E 69 uppercase E 89 w 119 lowercase w
40 F 70 uppercase F 90 x 120 lowercase x
41 G 71 uppercase G 91 y 121 lowercase y
42 H 72 uppercase H 92 z 122 lowercase z
43 I 73 uppercase I 93 { 123 left curly brace
44 J 74 uppercase J 94 | 124 vertical bar
45 K 75 uppercase K 95 } 125 right curly brace
46 L 76 uppercase L 96 ~ 126 tilde
47 M 77 uppercase M
48 N 78 uppercase N
49 O 79 uppercase O
50 P 80 uppercase P
NOTE:
YOUR ASSIGNMENTS WILL BE POSTED
TO YOUR RESPECTIVE GROUP FORUM.
PLEASE, WORK WITH YOUR GROUP
LEADERS NOT THE HOC.
THANK YOU !!!