0% found this document useful (0 votes)
16 views42 pages

Lecture Note 1A Introduction To C++ 17-10-2024

This document serves as an introductory lecture note for beginners learning C++. It covers the basics of C++, including its definition, differences from C, installation of IDEs, and fundamental programming concepts like variables, data types, and output statements. The document also provides examples and explanations of C++ syntax and coding practices.

Uploaded by

dreysaiah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views42 pages

Lecture Note 1A Introduction To C++ 17-10-2024

This document serves as an introductory lecture note for beginners learning C++. It covers the basics of C++, including its definition, differences from C, installation of IDEs, and fundamental programming concepts like variables, data types, and output statements. The document also provides examples and explanations of C++ syntax and coding practices.

Uploaded by

dreysaiah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

LECTURE NOTE 1A:

CSC201 INTRODUCTION TO C++


FOR THE BEGINNERS.
VERY INTERESTING FOR THE
FUTURE DEVELOPERS.
YOU ARE WELCOME TO C++
What is C++? C++ is a cross-platform language that can be used to create high-performance
applications. It was developed by Bjarne Stroustrup, as an extension to the C language. The
purpose is to allow programmers with good and a high level of control over system resources and
memory.
The language has been updated from version1 to versions5 as C++11, C++14, C++17, C++20,
and C++23 in the year 2011, 2014, 2017, 2020, and 2023 respectively. Please note that C++ is
very close to C, C# and Java, it makes it easy for programmers to switch to C++ or vice versa.
Why Use C++
C++ is one of the world's most popular programming languages. It can be found in recent
operating systems for Graphical User Interfaces (GUI), and other embedded systems profiles.
It is an object-oriented programming language which gives a clear structure to programs and
allows code to be reused, lowering development costs. It is also very portable and can be used to
develop applications that can be adapted to multiple platforms and devices.
C++ language is simplex and interesting to learn but you must make yourself available to pay
Difference between C and C++
C++ was developed as an extension of C, and both languages have almost the same syntax.
The main difference between C and C++ is that C++ support classes and objects, while C does not.
To start using C++, you need two things:
 A text editor, like Notepad, to write C++ code
 A compiler, like GNU Compiler Collection, (GCC), to translate the C++ code into a language that the computer
will understand. There are many text editors and compilers to choose from but in this class and the exercises, we
may likely be using an IDE editor.

C++ Install IDE


An IDE (Integrated Development Environment) is used to edit and compile the code in programming language. The
common one include: (i). Code::Blocks, (ii) Eclipse, and (ii). Visual Studio. These are all free, and they can be used
to both edit and debug C++ codes. Note: Web-based IDE's can work as well, but functionality is limited.
We will use Code::Blocks in our subsequent lectures, which we believe is a good starting point as a beginner.
NOTE: You can find the latest version of Codeblocks at http://www.codeblocks.org/. Download the mingw-
setup.exe file, which will install the text editor with a compiler. Or goto the software laboratory and approach the
technologists for assistant
C++ Quickstart (Let's create our first C++ file.)
Open Codeblocks and go to File > New > Empty File.Or, click on the icon on the desktop.
Write the following C++ code and save the file as myfirstprogram.cpp (File > Save File as):

Class example one:


myfirstC++program.cpp
#include <iostream>
using namespace std;

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.

Note: Every C++ statement ends with a semicolon ‘ ;’.


Note: The body of int main() could also been written as:
int main () { cout << " Beginners are always welcome to C++ programming skills! "; return 0; }
Remember: The compiler ignores white spaces. However, multiple lines make the code more readable.
Line 6: return 0; ends the main function.
Line 7: Do not forget to add the closing curly bracket } to actually end the main function
Omitting Namespace
You might see some C++ programs that runs without the standard namespace library. The using
namespace std line can be omitted and replaced with the std keyword, followed by the :: operator
for some objects:
Example:
#include <iostream>
int main() {
std::cout << " Beginners are always welcome to C++ programming skills!";
return 0;
}
C++ Statements A computer program is a list of "instructions" to be "executed" by a computer.
In a programming language, these programming instructions are called statements
The following statement "instructs" the compiler to print the text " Beginners are always
welcome to C++ programming skills!" to the screen:
Example
cout << " Beginners are always welcome to C++ programming skills!"
error: expected ';' before 'return'

Many Statements. Most C++ programs contain many statements.


The statements are executed, one by one, in the same order as they are written:
Example
cout << " Beginners are always welcome to C++ programming skills!";
cout << "Have a good day!";
return 0;
Example explained. From the example above, we have three statements:
1. cout << " Beginners are always welcome to C++ programming skills!";
2. cout << "Have a good day!";
3. return 0;
The first statement is executed first (print "Beginners are always welcome to C++
programming skills!" to the screen). Then the second statement is executed (print
"Have a good day!" to the screen). And at last, the third statement is executed (end
the C++ program successfully).
C++ Output (Print Text)
The cout object, together with the << operator, is used to output values and print
text. Just remember to surround the text with double quotes (""):
Example
#include <iostream>
using namespace std;
int main() {
cout << " Beginners are always welcome to C++ programming skills!";
return 0;
}
You can add as many cout objects as you want. However, note that it does not insert a new line at the end of the output:
Example
#include <iostream>
using namespace std;
int main() {
cout << " Beginners are always welcome to C++ programming skills!";
cout << "I am learning C++";
return 0;
}
C++ Print Numbers
You can also use cout() to print numbers. However, unlike text, we don't put numbers inside double quotes:
Example
#include <iostream>
using namespace std;
int main() {
cout << 3;
return 0;
}
Example
cout << 3 + 3;
Example
cout << 2 * 5;
New Lines
To insert a new line in your output, you can use the \n character:
Example
#include <iostream>
using namespace std;

int main() {
cout << " Beginners are always welcome to C++ programming skills!\n";

cout << "I am learning C++";


return 0;
}
You can also use another << operator and place the \n character after the text, like this:
Example
#include <iostream>
using namespace std;

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.

But what is exactly is \n called escape sequence?


The newline character (\n) is called an escape sequence, and it forces the cursor to change its position to the
beginning of the next line on the screen. This results in a new line.
Examples of other valid escape sequences are:
Escape Sequence Description
\t Creates a horizontal tab

\\ Inserts a backslash character (\)


\" Inserts a double quote character
C++ Comments
Comments can be used to explain C++ code, and to make it more readable. It can also be used
to prevent execution when testing alternative code. Comments can be singled-lined or multi-
lined.
Single-line Comments
Single-line comments start with two forward slashes (//).
Any text between // and the end of the line is ignored by the compiler (will not be executed).
This example uses a single-line comment before a line of code:
Example
// This is a comment
cout << "Beginners are always welcome to C++ programming skills!";
This example uses a single-line comment at the end of a line of code:
Example
C++ Multi-line Comments
Multi-line comments start with /* and ends with */.
Any text between /* and */ will be ignored by the compiler:
Example
/* The code below will print the words Beginners are always welcome to C++
programming skills!
to the screen, and it is amazing */
cout << "Beginners are always welcome to C++ programming skills!";

Single or multi-line comments?


It is up to you which you want to use. Normally, we use // for short comments,
and /* */ for longer
C++ Variables
Variables are containers for storing data values.
In C++, there are different types of variables (defined with different keywords),
for example:
i. int  stores integers (whole numbers), without decimals, such as 123 or -123
ii. double  stores floating point numbers, with decimals, such as 19.99 or -19.99
iii.char  stores single characters, such as 'a' or 'B'. Char values are surrounded
by single quotes
iv.string  stores text, such as "Hello World". String values are surrounded by
double quotes
v. bool  stores values with two states: true or false
Declaring (Creating) Variables
To create a variable, specify the type and assign it a value:
Syntax: type variableName = value;
Where type is one of C++ types (such as int), and variableName is the name of
the variable (such as x or myName). The equal sign is used to assign values to
the variable.

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";

// Output string value


cout << greeting;
C++ Data Types Examples
Real-Life Examples
Here's a real-life example of using different data types, to calculate and output the total cost of a
number of items:
Example
// Create variables of different data types
int items = 50;
double cost_per_item = 9.99;
double total_cost = items * cost_per_item;
char currency = '$';

// 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 !!!

You might also like