SlideShare a Scribd company logo
AMMAR AHMAD KHAN
WEEK 02 (3 & 4)
Programming Fundamentals
What is C++?
Introduction to C++
C++ is a cross-platform language that can be used to create high-
performance applications.
C++ was developed by Bjarne Stroustrup, as an extension to the C
language.
C++ gives programmers a high level of control over system resources and
memory.
The language was updated 5 major times in 2011, 2014, 2017, 2020, and
2023 to C++11, C++14, C++17, C++20, and C++23.
C++ Syntax
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
Line 1: #include <iostream> is a header
fi
le library that lets us work with input and output objects, such as cout (used in line 5). Header
fi
les add functionality to C++ programs.
Line 2: using namespace std means that we can use names for objects and variables from the standard library.
Line 3: A blank line. C++ ignores white space. But we use it to make the code more readable.
Line 4: Another thing that always appear in a C++ program is 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 "Hello World!".
Note: C++ is case-sensitive: "cout" and "Cout" has different meaning.
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 << "Hello World!";
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 "Hello World" to the screen:
Example
cout << "Hello World!";
• It is important that you end the statement with a semicolon ;
• If you forget the semicolon (;), an error will occur and the program will not run:
Example
cout << "Hello World!"
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 << "Hello World!";
cout << "Have a good day!";
return 0;
Example explained
From the example above, we have three statements:
1.cout << "Hello World!";
2.cout << "Have a good day!";
3.return 0;
The
fi
rst statement is executed
fi
rst (print "Hello World!" 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 << "Hello World!";
return 0;
}
C++ Output (Print Text)
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 << "Hello World!";
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;
}
You can also perform mathematical calculations:
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 << "Hello World! 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 << "Hello World!" << "n";
cout << "I am learning C++";
return 0;
}
New Lines
Tip: Two n characters after each other will create a blank line:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << "nn";
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 << "Hello World!" << endl;
cout << "I am learning C++";
return 0;
}
New Lines
Both n and endl are used to break lines. However, n is most used.
But what is n exactly?
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:
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 << "Hello World!";
C++ Comments
This example uses a single-line comment at the end of a line of code:
Example
cout << "Hello World!"; // This is a comment
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 Hello World!
to the screen, and it is amazing */
cout << "Hello World!";
C++ Variables
Variables are containers for storing data values.
In C++, there are different types of variables (de
fi
ned with different keywords), for
example:
• int - stores integers (whole numbers), without decimals, such as 123 or -123
• double - stores
fl
oating point numbers, with decimals, such as 19.99 or -19.99
• char - stores single characters, such as 'a' or 'B'. Char values are surrounded by
single quotes
• string - stores text, such as "Hello World". String values are surrounded by double
quotes
• 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;
Declaring (Creating) Variables
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; // Output 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;
Display 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++ Identi
fi
ers
• All C++ variables must be identi
fi
ed with unique names.
• These unique names are called identi
fi
ers.
• Identi
fi
ers 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 are:
•Names can contain letters, digits and underscores
•Names must begin with a letter or an underscore (_)
•Names are case-sensitive (myVar and myvar are different variables)
•Names cannot contain whitespaces or special characters like !, #, %, etc.
•Reserved words (like C++ keywords, such as int) cannot be used as names
Constants
• When you do not want others (or yourself) to change existing variable values, use
the constkeyword (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
fl
oat PI = 3.14;
Notes On Constants
• When you declare a constant variable, it must be assigned with a value:
Example
Like this:
const int minutesPerHour = 60;
This however, will not work:
const int minutesPerHour;
minutesPerHour = 60; // error
Variable Example
Write a C++ program that stores a student's details such as student ID,
age, fee, and grade using appropriate data types. Then, print these
details in a readable format using cout.
Write a C++ program to calculate the area of a rectangle.
Initialize length = 4 and width = 6, then compute and print the area.
C++ User Input
• You have already learned that cout is used to output (print) values.
• Now we will use cin to get user input.
cin is a prede
fi
ned variable that reads data from the keyboard with the extraction operator
(>>).
In the following example, the user can input a number, which is stored in the variable x. Then
we print the value of x:
Example
int x;
cout << "Type a number: "; // Type a number and press enter
cin >> x; // Get user input from the keyboard
cout << "Your number is: " << x; // Display the input value
C++ User Input
Good To Know
• cout is pronounced "see-out". Used for output, and uses the insertion operator (<<)
• cin is pronounced "see-in". Used for input, and uses the extraction operator (>>)
Creating a Simple Calculator
Write a program in which the user must input two numbers. Then we print the sum by calculating
(adding) the two numbers.
C++ Data Types
• As explained in the Variables slides, a variable in C++ must be a speci
fi
ed
data type:
Example
int myNum = 5; // Integer (whole number)
fl
oat 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
Basic Data Types
•The data type speci
fi
es the size and type of information the variable will store:
D
a
t
a
Type Size Description
boole
a
n 1 byte Stores true or false values
ch
a
r 1 byte
Stores a single character/letter/number, or ASCII
values
int 2 or 4 bytes Stores whole numbers, without decimals
f
lo
a
t 4 bytes
Stores fractional numbers, containing one or more
decimals. Suf
fi
cient for storing 6-7 decimal digits
Double 8 bytes
Stores fractional numbers, containing one or more
decimals. Suf
fi
cient for storing 15 decimal digits
Numeric Types
• Use int when you need to store a whole number without decimals, like 35 or 1000,
and
fl
oat or double when you need a
fl
oating point number (with decimals), like 9.99 or
3.14515.
int
int myNum = 1000;
cout << myNum;
fl
oat
fl
oat myNum = 5.75;
cout << myNum;
Numeric Types
double
double myNum = 19.99;
cout << myNum;
fl
oat vs. double
The precision of a
fl
oating point value indicates how many digits the value can have after the decimal
point. The precision of
fl
oat 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.
Scienti
fi
c Numbers
• A
fl
oating point number can also be a scienti
fi
c number with an "e" to indicate the power of 10:
Example
fl
oat f1 = 35e3;
double d1 = 12E4;
cout << f1;
cout << d1;
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)
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;
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;
• To use strings, you must include an additional header
fi
le 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;
Write a C++ program to calculate the total cost of items in a
store. The program should:
1.Create an integer variable items initialized to 50.
2.Create a double variable cost_per_item initialized to 9.99.
3.Calculate the total cost as total_cost = items *
cost_per_item.
4.Create a char variable currency initialized to '$'.
5.Print the number of items, cost per item, and the total cost
with the currency symbol.
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
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Logical operators
5. Bitwise 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:
Comparison Operators
• Comparison operators are used to compare two values (or variables). This is
important in programming, because it helps us to
fi
nd answers and make decisions.
• The return value of a comparison is either 1 or 0, which means true (1) or false (0).
In the following example, we use the greater than operator (>) to
fi
nd out if 5 is greater
than 3:
Example
int x = 5;
int y = 3;
cout << (x > y); // returns 1 (true) because 5 is greater than 3
A list of all comparison operators:
Logical Operators
• As with comparison operators, you can also test for true (1) or false (0) values with logical
operators.
Logical operators are used to determine the logic between variables or values:

More Related Content

Similar to PROGRAMMING FUNDAMENTALS BASICS LECTURE 2 (20)

Pengaturcaraan asas
Pengaturcaraan asasPengaturcaraan asas
Pengaturcaraan asas
Unit Kediaman Luar Kampus
 
C++ Introduction C+ Conditions.pptx.pptx
C++ Introduction C+ Conditions.pptx.pptxC++ Introduction C+ Conditions.pptx.pptx
C++ Introduction C+ Conditions.pptx.pptx
MAHERMOHAMED27
 
Introduction to C++,Computer Science
Introduction to C++,Computer ScienceIntroduction to C++,Computer Science
Introduction to C++,Computer Science
Abhinav Vishnoi
 
Intro cpp
Intro cppIntro cpp
Intro cpp
hamza239523
 
clc02_cpp_presentation_edit3 (1) 1.pptx
clc02_cpp_presentation_edit3 (1) 1.pptxclc02_cpp_presentation_edit3 (1) 1.pptx
clc02_cpp_presentation_edit3 (1) 1.pptx
jminrin0212
 
Intro in understanding to C programming .pptx
Intro in understanding to C   programming .pptxIntro in understanding to C   programming .pptx
Intro in understanding to C programming .pptx
abadinasargie
 
computer ppt group22222222222222222222 (1).pptx
computer ppt group22222222222222222222 (1).pptxcomputer ppt group22222222222222222222 (1).pptx
computer ppt group22222222222222222222 (1).pptx
JoyLedda3
 
Programming fundamental 02.pptx
Programming fundamental 02.pptxProgramming fundamental 02.pptx
Programming fundamental 02.pptx
ZubairAli256321
 
#Code2 create c++ for beginners
#Code2 create  c++ for beginners #Code2 create  c++ for beginners
#Code2 create c++ for beginners
GDGKuwaitGoogleDevel
 
Programming Fundamentals
Programming FundamentalsProgramming Fundamentals
Programming Fundamentals
Zohaib Sharif
 
C++ L01-Variables
C++ L01-VariablesC++ L01-Variables
C++ L01-Variables
Mohammad Shaker
 
Tutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng verTutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng ver
Qrembiezs Intruder
 
Elementary_Of_C++_Programming_Language.ppt
Elementary_Of_C++_Programming_Language.pptElementary_Of_C++_Programming_Language.ppt
Elementary_Of_C++_Programming_Language.ppt
GordanaJovanoska1
 
Lecture 1 Introduction C++
Lecture 1 Introduction C++Lecture 1 Introduction C++
Lecture 1 Introduction C++
Ajay Khatri
 
Introduction to cpp language and all the required information relating to it
Introduction to cpp language and all the required information relating to itIntroduction to cpp language and all the required information relating to it
Introduction to cpp language and all the required information relating to it
PushkarNiroula1
 
C++ language basic
C++ language basicC++ language basic
C++ language basic
Waqar Younis
 
C++ lesson variables.pptx
C++ lesson variables.pptxC++ lesson variables.pptx
C++ lesson variables.pptx
Cynthia Agabin
 
Prog1-L1.pdf
Prog1-L1.pdfProg1-L1.pdf
Prog1-L1.pdf
valerie5142000
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
Ahmad Idrees
 
AS TASKS #8
AS TASKS #8AS TASKS #8
AS TASKS #8
NikkNakss
 
C++ Introduction C+ Conditions.pptx.pptx
C++ Introduction C+ Conditions.pptx.pptxC++ Introduction C+ Conditions.pptx.pptx
C++ Introduction C+ Conditions.pptx.pptx
MAHERMOHAMED27
 
Introduction to C++,Computer Science
Introduction to C++,Computer ScienceIntroduction to C++,Computer Science
Introduction to C++,Computer Science
Abhinav Vishnoi
 
clc02_cpp_presentation_edit3 (1) 1.pptx
clc02_cpp_presentation_edit3 (1) 1.pptxclc02_cpp_presentation_edit3 (1) 1.pptx
clc02_cpp_presentation_edit3 (1) 1.pptx
jminrin0212
 
Intro in understanding to C programming .pptx
Intro in understanding to C   programming .pptxIntro in understanding to C   programming .pptx
Intro in understanding to C programming .pptx
abadinasargie
 
computer ppt group22222222222222222222 (1).pptx
computer ppt group22222222222222222222 (1).pptxcomputer ppt group22222222222222222222 (1).pptx
computer ppt group22222222222222222222 (1).pptx
JoyLedda3
 
Programming fundamental 02.pptx
Programming fundamental 02.pptxProgramming fundamental 02.pptx
Programming fundamental 02.pptx
ZubairAli256321
 
Programming Fundamentals
Programming FundamentalsProgramming Fundamentals
Programming Fundamentals
Zohaib Sharif
 
Tutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng verTutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng ver
Qrembiezs Intruder
 
Elementary_Of_C++_Programming_Language.ppt
Elementary_Of_C++_Programming_Language.pptElementary_Of_C++_Programming_Language.ppt
Elementary_Of_C++_Programming_Language.ppt
GordanaJovanoska1
 
Lecture 1 Introduction C++
Lecture 1 Introduction C++Lecture 1 Introduction C++
Lecture 1 Introduction C++
Ajay Khatri
 
Introduction to cpp language and all the required information relating to it
Introduction to cpp language and all the required information relating to itIntroduction to cpp language and all the required information relating to it
Introduction to cpp language and all the required information relating to it
PushkarNiroula1
 
C++ language basic
C++ language basicC++ language basic
C++ language basic
Waqar Younis
 
C++ lesson variables.pptx
C++ lesson variables.pptxC++ lesson variables.pptx
C++ lesson variables.pptx
Cynthia Agabin
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
Ahmad Idrees
 

Recently uploaded (20)

Learnable and Expressive Visualization Authoring through Blended Interfaces
Learnable and Expressive Visualization Authoring through Blended InterfacesLearnable and Expressive Visualization Authoring through Blended Interfaces
Learnable and Expressive Visualization Authoring through Blended Interfaces
sehilyi
 
Schizophrenia AB (4) notes post graduate degree
Schizophrenia AB (4) notes post graduate degreeSchizophrenia AB (4) notes post graduate degree
Schizophrenia AB (4) notes post graduate degree
aiswaryavvg
 
IPA Science Quiz for competitions related
IPA Science Quiz for competitions relatedIPA Science Quiz for competitions related
IPA Science Quiz for competitions related
vkheraj
 
Comparative anatomy of brain of different types of vertebrates
Comparative anatomy of brain of different types of vertebratesComparative anatomy of brain of different types of vertebrates
Comparative anatomy of brain of different types of vertebrates
arpanmaji480
 
Campbell Biology Chapter 2 & 3 - HANDOUT-3.pdf
Campbell Biology Chapter 2 & 3 - HANDOUT-3.pdfCampbell Biology Chapter 2 & 3 - HANDOUT-3.pdf
Campbell Biology Chapter 2 & 3 - HANDOUT-3.pdf
maylordbewithyoujian
 
Multi-View Design Patterns & 
Responsive Visualization for
Genomics Data
Multi-View Design Patterns & 
Responsive Visualization for
Genomics DataMulti-View Design Patterns & 
Responsive Visualization for
Genomics Data
Multi-View Design Patterns & 
Responsive Visualization for
Genomics Data
sehilyi
 
hybridoma technology and Monoclonal_antibodies.pptx
hybridoma technology and Monoclonal_antibodies.pptxhybridoma technology and Monoclonal_antibodies.pptx
hybridoma technology and Monoclonal_antibodies.pptx
aqsarehman5055
 
Introduction-to-Water-Pollution1234.pptx
Introduction-to-Water-Pollution1234.pptxIntroduction-to-Water-Pollution1234.pptx
Introduction-to-Water-Pollution1234.pptx
shilpakadf
 
The scientific heritage No 161 (161) (2025)
The scientific heritage No 161 (161) (2025)The scientific heritage No 161 (161) (2025)
The scientific heritage No 161 (161) (2025)
The scientific heritage
 
CloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy Texts
CloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy TextsCloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy Texts
CloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy Texts
sehilyi
 
Decipher the Magic of Quantum Entanglement.pdf
Decipher the Magic of Quantum Entanglement.pdfDecipher the Magic of Quantum Entanglement.pdf
Decipher the Magic of Quantum Entanglement.pdf
SaikatBasu37
 
Science in retreat: The consequences for the Arctic and our planet
Science in retreat: The consequences for the Arctic and our planetScience in retreat: The consequences for the Arctic and our planet
Science in retreat: The consequences for the Arctic and our planet
Zachary Labe
 
Toward Understanding Representation Methods in Visualization Recommendations ...
Toward Understanding Representation Methods in Visualization Recommendations ...Toward Understanding Representation Methods in Visualization Recommendations ...
Toward Understanding Representation Methods in Visualization Recommendations ...
sehilyi
 
AFFORDABLE IT Software Development India
AFFORDABLE IT Software Development IndiaAFFORDABLE IT Software Development India
AFFORDABLE IT Software Development India
Affordable Cross-Platform App Developers
 
Medical Instrumentation -I Biological Signals .pptx
Medical Instrumentation -I Biological Signals .pptxMedical Instrumentation -I Biological Signals .pptx
Medical Instrumentation -I Biological Signals .pptx
drmaneharshalid
 
Radiation pressure (1).tygfyhjjjbcdssfvvjj
Radiation pressure (1).tygfyhjjjbcdssfvvjjRadiation pressure (1).tygfyhjjjbcdssfvvjj
Radiation pressure (1).tygfyhjjjbcdssfvvjj
Debaprasad16
 
Chapter 3 File and Folder Management.pptx
Chapter 3 File and Folder Management.pptxChapter 3 File and Folder Management.pptx
Chapter 3 File and Folder Management.pptx
deejayrakib5
 
Grammar-Based 
Interactive Visualization of Genomics Data
Grammar-Based 
Interactive Visualization of Genomics DataGrammar-Based 
Interactive Visualization of Genomics Data
Grammar-Based 
Interactive Visualization of Genomics Data
sehilyi
 
Treatment of TMDS.by Dr.Devraj Neupane(MDS Resedent)
Treatment of TMDS.by Dr.Devraj Neupane(MDS Resedent)Treatment of TMDS.by Dr.Devraj Neupane(MDS Resedent)
Treatment of TMDS.by Dr.Devraj Neupane(MDS Resedent)
Dr.Devraj Neupane
 
Chapter 18 Energy and Metabolism Energy Production 2017 [Compatibility Mode].pdf
Chapter 18 Energy and Metabolism Energy Production 2017 [Compatibility Mode].pdfChapter 18 Energy and Metabolism Energy Production 2017 [Compatibility Mode].pdf
Chapter 18 Energy and Metabolism Energy Production 2017 [Compatibility Mode].pdf
nigeldkdc54
 
Learnable and Expressive Visualization Authoring through Blended Interfaces
Learnable and Expressive Visualization Authoring through Blended InterfacesLearnable and Expressive Visualization Authoring through Blended Interfaces
Learnable and Expressive Visualization Authoring through Blended Interfaces
sehilyi
 
Schizophrenia AB (4) notes post graduate degree
Schizophrenia AB (4) notes post graduate degreeSchizophrenia AB (4) notes post graduate degree
Schizophrenia AB (4) notes post graduate degree
aiswaryavvg
 
IPA Science Quiz for competitions related
IPA Science Quiz for competitions relatedIPA Science Quiz for competitions related
IPA Science Quiz for competitions related
vkheraj
 
Comparative anatomy of brain of different types of vertebrates
Comparative anatomy of brain of different types of vertebratesComparative anatomy of brain of different types of vertebrates
Comparative anatomy of brain of different types of vertebrates
arpanmaji480
 
Campbell Biology Chapter 2 & 3 - HANDOUT-3.pdf
Campbell Biology Chapter 2 & 3 - HANDOUT-3.pdfCampbell Biology Chapter 2 & 3 - HANDOUT-3.pdf
Campbell Biology Chapter 2 & 3 - HANDOUT-3.pdf
maylordbewithyoujian
 
Multi-View Design Patterns & 
Responsive Visualization for
Genomics Data
Multi-View Design Patterns & 
Responsive Visualization for
Genomics DataMulti-View Design Patterns & 
Responsive Visualization for
Genomics Data
Multi-View Design Patterns & 
Responsive Visualization for
Genomics Data
sehilyi
 
hybridoma technology and Monoclonal_antibodies.pptx
hybridoma technology and Monoclonal_antibodies.pptxhybridoma technology and Monoclonal_antibodies.pptx
hybridoma technology and Monoclonal_antibodies.pptx
aqsarehman5055
 
Introduction-to-Water-Pollution1234.pptx
Introduction-to-Water-Pollution1234.pptxIntroduction-to-Water-Pollution1234.pptx
Introduction-to-Water-Pollution1234.pptx
shilpakadf
 
The scientific heritage No 161 (161) (2025)
The scientific heritage No 161 (161) (2025)The scientific heritage No 161 (161) (2025)
The scientific heritage No 161 (161) (2025)
The scientific heritage
 
CloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy Texts
CloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy TextsCloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy Texts
CloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy Texts
sehilyi
 
Decipher the Magic of Quantum Entanglement.pdf
Decipher the Magic of Quantum Entanglement.pdfDecipher the Magic of Quantum Entanglement.pdf
Decipher the Magic of Quantum Entanglement.pdf
SaikatBasu37
 
Science in retreat: The consequences for the Arctic and our planet
Science in retreat: The consequences for the Arctic and our planetScience in retreat: The consequences for the Arctic and our planet
Science in retreat: The consequences for the Arctic and our planet
Zachary Labe
 
Toward Understanding Representation Methods in Visualization Recommendations ...
Toward Understanding Representation Methods in Visualization Recommendations ...Toward Understanding Representation Methods in Visualization Recommendations ...
Toward Understanding Representation Methods in Visualization Recommendations ...
sehilyi
 
Medical Instrumentation -I Biological Signals .pptx
Medical Instrumentation -I Biological Signals .pptxMedical Instrumentation -I Biological Signals .pptx
Medical Instrumentation -I Biological Signals .pptx
drmaneharshalid
 
Radiation pressure (1).tygfyhjjjbcdssfvvjj
Radiation pressure (1).tygfyhjjjbcdssfvvjjRadiation pressure (1).tygfyhjjjbcdssfvvjj
Radiation pressure (1).tygfyhjjjbcdssfvvjj
Debaprasad16
 
Chapter 3 File and Folder Management.pptx
Chapter 3 File and Folder Management.pptxChapter 3 File and Folder Management.pptx
Chapter 3 File and Folder Management.pptx
deejayrakib5
 
Grammar-Based 
Interactive Visualization of Genomics Data
Grammar-Based 
Interactive Visualization of Genomics DataGrammar-Based 
Interactive Visualization of Genomics Data
Grammar-Based 
Interactive Visualization of Genomics Data
sehilyi
 
Treatment of TMDS.by Dr.Devraj Neupane(MDS Resedent)
Treatment of TMDS.by Dr.Devraj Neupane(MDS Resedent)Treatment of TMDS.by Dr.Devraj Neupane(MDS Resedent)
Treatment of TMDS.by Dr.Devraj Neupane(MDS Resedent)
Dr.Devraj Neupane
 
Chapter 18 Energy and Metabolism Energy Production 2017 [Compatibility Mode].pdf
Chapter 18 Energy and Metabolism Energy Production 2017 [Compatibility Mode].pdfChapter 18 Energy and Metabolism Energy Production 2017 [Compatibility Mode].pdf
Chapter 18 Energy and Metabolism Energy Production 2017 [Compatibility Mode].pdf
nigeldkdc54
 
Ad

PROGRAMMING FUNDAMENTALS BASICS LECTURE 2

  • 1. AMMAR AHMAD KHAN WEEK 02 (3 & 4) Programming Fundamentals
  • 2. What is C++? Introduction to C++ C++ is a cross-platform language that can be used to create high- performance applications. C++ was developed by Bjarne Stroustrup, as an extension to the C language. C++ gives programmers a high level of control over system resources and memory. The language was updated 5 major times in 2011, 2014, 2017, 2020, and 2023 to C++11, C++14, C++17, C++20, and C++23.
  • 3. C++ Syntax Example #include <iostream> using namespace std; int main() { cout << "Hello World!"; return 0; } Line 1: #include <iostream> is a header fi le library that lets us work with input and output objects, such as cout (used in line 5). Header fi les add functionality to C++ programs. Line 2: using namespace std means that we can use names for objects and variables from the standard library. Line 3: A blank line. C++ ignores white space. But we use it to make the code more readable. Line 4: Another thing that always appear in a C++ program is 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 "Hello World!". Note: C++ is case-sensitive: "cout" and "Cout" has different meaning. 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.
  • 4. 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 << "Hello World!"; return 0; }
  • 5. 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 "Hello World" to the screen: Example cout << "Hello World!"; • It is important that you end the statement with a semicolon ; • If you forget the semicolon (;), an error will occur and the program will not run: Example cout << "Hello World!" error: expected ';' before 'return'
  • 6. 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 << "Hello World!"; cout << "Have a good day!"; return 0; Example explained From the example above, we have three statements: 1.cout << "Hello World!"; 2.cout << "Have a good day!"; 3.return 0; The fi rst statement is executed fi rst (print "Hello World!" 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).
  • 7. 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 << "Hello World!"; return 0; }
  • 8. C++ Output (Print Text) 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 << "Hello World!"; cout << "I am learning C++"; return 0; }
  • 9. 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; } You can also perform mathematical calculations: Example cout << 3 + 3; Example cout << 2 * 5;
  • 10. 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 << "Hello World! 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 << "Hello World!" << "n"; cout << "I am learning C++"; return 0; }
  • 11. New Lines Tip: Two n characters after each other will create a blank line: Example #include <iostream> using namespace std; int main() { cout << "Hello World!" << "nn"; 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 << "Hello World!" << endl; cout << "I am learning C++"; return 0; }
  • 12. New Lines Both n and endl are used to break lines. However, n is most used. But what is n exactly? 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: t Creates a horizontal tab Inserts a backslash character () ” Inserts a double quote character
  • 13. 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 << "Hello World!";
  • 14. C++ Comments This example uses a single-line comment at the end of a line of code: Example cout << "Hello World!"; // This is a comment 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 Hello World! to the screen, and it is amazing */ cout << "Hello World!";
  • 15. C++ Variables Variables are containers for storing data values. In C++, there are different types of variables (de fi ned with different keywords), for example: • int - stores integers (whole numbers), without decimals, such as 123 or -123 • double - stores fl oating point numbers, with decimals, such as 19.99 or -19.99 • char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes • string - stores text, such as "Hello World". String values are surrounded by double quotes • bool - stores values with two states: true or false
  • 16. 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;
  • 17. Declaring (Creating) Variables 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; // Output 10
  • 18. 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)
  • 19. 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;
  • 20. Display 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;
  • 21. C++ Identi fi ers • All C++ variables must be identi fi ed with unique names. • These unique names are called identi fi ers. • Identi fi ers 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;
  • 22. The general rules for naming variables are: •Names can contain letters, digits and underscores •Names must begin with a letter or an underscore (_) •Names are case-sensitive (myVar and myvar are different variables) •Names cannot contain whitespaces or special characters like !, #, %, etc. •Reserved words (like C++ keywords, such as int) cannot be used as names
  • 23. Constants • When you do not want others (or yourself) to change existing variable values, use the constkeyword (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 fl oat PI = 3.14;
  • 24. Notes On Constants • When you declare a constant variable, it must be assigned with a value: Example Like this: const int minutesPerHour = 60; This however, will not work: const int minutesPerHour; minutesPerHour = 60; // error
  • 25. Variable Example Write a C++ program that stores a student's details such as student ID, age, fee, and grade using appropriate data types. Then, print these details in a readable format using cout. Write a C++ program to calculate the area of a rectangle. Initialize length = 4 and width = 6, then compute and print the area.
  • 26. C++ User Input • You have already learned that cout is used to output (print) values. • Now we will use cin to get user input. cin is a prede fi ned variable that reads data from the keyboard with the extraction operator (>>). In the following example, the user can input a number, which is stored in the variable x. Then we print the value of x: Example int x; cout << "Type a number: "; // Type a number and press enter cin >> x; // Get user input from the keyboard cout << "Your number is: " << x; // Display the input value
  • 27. C++ User Input Good To Know • cout is pronounced "see-out". Used for output, and uses the insertion operator (<<) • cin is pronounced "see-in". Used for input, and uses the extraction operator (>>) Creating a Simple Calculator Write a program in which the user must input two numbers. Then we print the sum by calculating (adding) the two numbers.
  • 28. C++ Data Types • As explained in the Variables slides, a variable in C++ must be a speci fi ed data type: Example int myNum = 5; // Integer (whole number) fl oat 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
  • 29. Basic Data Types •The data type speci fi es the size and type of information the variable will store: D a t a Type Size Description boole a n 1 byte Stores true or false values ch a r 1 byte Stores a single character/letter/number, or ASCII values int 2 or 4 bytes Stores whole numbers, without decimals f lo a t 4 bytes Stores fractional numbers, containing one or more decimals. Suf fi cient for storing 6-7 decimal digits Double 8 bytes Stores fractional numbers, containing one or more decimals. Suf fi cient for storing 15 decimal digits
  • 30. Numeric Types • Use int when you need to store a whole number without decimals, like 35 or 1000, and fl oat or double when you need a fl oating point number (with decimals), like 9.99 or 3.14515. int int myNum = 1000; cout << myNum; fl oat fl oat myNum = 5.75; cout << myNum;
  • 31. Numeric Types double double myNum = 19.99; cout << myNum; fl oat vs. double The precision of a fl oating point value indicates how many digits the value can have after the decimal point. The precision of fl oat 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. Scienti fi c Numbers • A fl oating point number can also be a scienti fi c number with an "e" to indicate the power of 10: Example fl oat f1 = 35e3; double d1 = 12E4; cout << f1; cout << d1;
  • 32. 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)
  • 33. 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;
  • 34. 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; • To use strings, you must include an additional header fi le 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;
  • 35. Write a C++ program to calculate the total cost of items in a store. The program should: 1.Create an integer variable items initialized to 50. 2.Create a double variable cost_per_item initialized to 9.99. 3.Calculate the total cost as total_cost = items * cost_per_item. 4.Create a char variable currency initialized to '$'. 5.Print the number of items, cost per item, and the total cost with the currency symbol.
  • 36. 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)
  • 37. C++ divides the operators into the following 1. Arithmetic operators 2. Assignment operators 3. Comparison operators 4. Logical operators 5. Bitwise operators
  • 38. 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;
  • 39. A list of all assignment operators:
  • 40. Comparison Operators • Comparison operators are used to compare two values (or variables). This is important in programming, because it helps us to fi nd answers and make decisions. • The return value of a comparison is either 1 or 0, which means true (1) or false (0). In the following example, we use the greater than operator (>) to fi nd out if 5 is greater than 3: Example int x = 5; int y = 3; cout << (x > y); // returns 1 (true) because 5 is greater than 3
  • 41. A list of all comparison operators:
  • 42. Logical Operators • As with comparison operators, you can also test for true (1) or false (0) values with logical operators. Logical operators are used to determine the logic between variables or values: