Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

C++ OOPs Programming Basics

Uploaded by

bashirkhankk44
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

C++ OOPs Programming Basics

Uploaded by

bashirkhankk44
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 51

PROGRAMMING

C++
SIR. SAIF WIYAR
COURSE OUTLINE

ASSESSMENT

COURSEWORK AND PROJECT

Assignments 20%

Class Activity 10%

Presentations 10%

Midterm Exam 20%

Final Term Exam 60%

TOTAL 100%
WHAT IS PROGRAMMING LANGUAGE

• Programming is the process of creating a set of instructions that tell a computer how to perform a
task. These instructions are written using various programming languages, such as JavaScript,
Python, and C++…
• Programming is a collaboration between humans and computers.
• It involves designing and implementing algorithms, which are step-by-step specifications of
procedures.
• Programming enables many things in our lives, from browsing websites to using mobile apps.
• Different programming languages enable programmers to write code that computers
understand. Some of the most used programming languages are JavaScript, Python, and C++.
C++ PROGRAMMING LANGUAGE

• C++ is an object-oriented programming language. It is an extension to C programming.

• Our C++ tutorial includes all topics of C++ such as first example, control statements, objects and classes,
inheritance, constructor, destructor, this, static, polymorphism, abstraction, abstract class, interface, namespace,
encapsulation, arrays, strings, exception handling, File IO, etc.
WHAT IS C++

• C++ is a general purpose, case-sensitive and supports object-oriented, procedural and generic
programming.

• C++ is a middle-level language, as it encapsulates both high and low level language features.

• C++ is a cross-platform language that can be used to create high-performance applications.

• C++ was developed by Bjarne Stroustrup, in 1980 as an extension to the C language.

• C++ gives programmers a high level of control over system resources and memory.

• The language was updated 4 major times in 2011, 2014, 2017, and 2020 to C++11, C++14, C++17, C++20
OBJECT-ORIENTED PROGRAMMING (OOPS)

• C++ supports the object-oriented programming, the four major pillar of object-oriented programming (OOPs)
used in C++ are:

1. Inheritance

2. Polymorphism

3. Encapsulation

4. Abstraction
USAGE OF C++

• By the help of C++ programming language, we can develop different types of secured and robust applications:

• Window application

• Client-Server application

• Device drivers

• Embedded firmware etc


WHY USE C++

• C++ is one of the world's most popular programming languages.

• C++ can be found in today's operating systems, Graphical User Interfaces, and embedded systems.

• C++ is an object-oriented programming language which gives a clear structure to programs and allows code to
be reused, lowering development costs.

• C++ is portable and can be used to develop applications that can be adapted to multiple platforms.

• C++ is fun and easy to learn!

• As C++ is close to C, C# and Java, it makes it easy for programmers to switch to C++ or vice versa
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
C++ STARTED

• To start using C++, you need two things:

• A text editor, like Notepad, to write C++ code

• A compiler, like GCC, to translate the C++ code into a language that the computer will understand

• There are many text editors and compilers to choose from. In this tutorial, we will use an IDE (see below)
• #include <iostream>
using namespace std;

int main() {
cout << "Hello World!";
return 0;
}
C++ SYNTAX

• 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

• Line 3: space

• Line 3: 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!“

• Line 6: return 0 ends the main function


C++ OUTPUT (PRINT TEXT)

• The cout object, together with the << operator, is used to output values/print text

• New Lines
• To insert a new line, you can use the \n character

• Two \n\n characters after each other will create a blank line
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)

• C++ Multi-line Comments

• Multi-line comments start with /* and ends with */.

• Any text between /* and */ will be ignored by the compiler


C++ VARIABLES

• Variables are containers for storing data values

• In C++, there are different types of variables (defined with different keywords), for example:

• int - stores integers (whole numbers), without decimals, such as 123 or -123

• double - stores floating 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

• Boolean - stores values with two states: true or false


DECLARING (CREATING) VARIABLES

• To create a variable, specify the type and assign it a value


• Where type is one of C++ types (such as int), and variable Name is the name of the variable (such as
x or myName). The equal sign is used to assign values to the variable
• 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

• Add Variables Together

• To add a variable to another variable, you can use the + operator

• int myNum;
myNum = 15;
cout << myNum;
DECLARE MANY VARIABLES

• int x = 5, y = 6, z = 50;

• cout << x + y + z;

• One Value to Multiple Variables

• 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)

• All C++ variables must be identified with unique names.

• 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
C++ 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)

• 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 predefined 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:

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


SIMPLE CALCULATOR

• int x, y;
• int sum;
• cout << "Type a number: ";
• cin >> x;
• cout << "Type another number: ";
• cin >> y;
• sum = x + y;
• cout << "Sum is: " << sum;
DATA TYPES

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
float 4 bytes Stores fractional numbers,
containing one or more
decimals. Sufficient for storing
6-7 decimal digits
double 8 bytes Stores fractional numbers,
containing one or more
decimals. Sufficient for storing
15 decimal digits
C++ OPERATORS

• Operators are used to perform operations on variables and values.


• C++ divides the operators into the following groups:

• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
ARITHMETIC OPERATORS

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 are used to assign values to variables


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
COMPARISON OPERATORS

• Comparison operators are used to compare two values (or variables). This is important in
programming, because it helps us to find answers and make decisions.

• The return value of a comparison is either 1 or 0, which means true (1) or false (0). These values
are known as Boolean values, and you will learn more about them in the Booleans and If..Else .

Operator Name Example


== Equal to x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
LOGICAL OPERATORS

• As with comparison operators, you can also test for true (1) or false (0)
values with logical operators.

Operator Name Description Example


Logical Returns true if both x < 5 && x < 10
&&
and statements are true
Logical or Returns true if one of the x < 5 || x < 4
||
statements is true
Logical Reverse the result, returns !(x < 5 && x <
!
not false if the result is true 10)
C++ STRINGS

• A string variable contains a collection of characters surrounded by double quotes:


• string greeting = "Hello";

• cout << greeting;


• C++ String Concatenation:

• The + operator can be used between strings to add them together to make a new string. This is called
concatenation
• string firstName = "John ";

• string lastName = "Doe";

• string fullName = firstName + lastName; firstName.append(lastName);


• cout << fullName;
C++ NUMBERS AND STRINGS

• string x = "10";

• string y = "20";

• string z = x + y;

• String Length:

• To get the length of a string, use the length() function:


• string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

• cout << "The length of the txt string is: " << txt.length();
BOOLEAN EXPRESSION

• A Boolean expression returns a boolean value that is either 1 (true) or 0


(false)
• int x = 10;

• int y = 9;

• cout << (x > y);


CONDITIONS AND IF STATEMENTS:

• Less than: a < b


• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
• Equal to a == b
• Not Equal to: a != b
• You can use these conditions to perform different actions for different decisions.

• C++ has the following conditional statements:

• Use if to specify a block of code to be executed, if a specified condition is true


• Use else to specify a block of code to be executed, if the same condition is false
• Use else if to specify a new condition to test, if the first condition is false
• Use switch to specify many alternative blocks of code to be executed
EXAMPLE

• int x = 20;

• int y = 18;

• if (x > y) {

• cout << "x is greater than y";

• }

• else Statement:
• Use the else statement to specify a block of code to be executed if the condition is false

• else {
• cout << "Good evening.";
• }
ELSE IF STATEMENT

• Use the else if statement to specify a new condition if the first condition
is false.
• int time = 22;

• if (time < 10) {

• cout << "Good morning.";

• } else if (time < 20) {

• cout << "Good day.";

• }
C++ SWITCH

• Use the switch statement to select one of many code blocks to be executed.
• int day = 4;

• switch (day) {

• case 1:

• cout << "Monday";

• break;

• case 2:

• break Keyword:
• When C++ reaches a break keyword, it breaks out of the switch block.
• This will stop the execution of more code and case testing inside the block.
• When a match is found, and the job is done, it's time for a break. There is no need for more testing.
DEFAULT KEYWORD

• The default keyword specifies some code to run if there is no case


match:
• cout << "Today is Sunday";

• break;

• default:

• cout << "Looking forward to the Weekend";

• }
WHILE LOOP

• Loops
• Loops can execute a block of code as long as a specified condition is reached.
• Loops are handy because they save time, reduce errors, and they make code more readable.
• The while loop loops through a block of code as long as a specified condition is true:
• int i = 0;
• while (i < 5) {
• cout << i << "\n";
• i++;
• }
DO/WHILE LOOP

• The do/while loop is a variant of the while loop. This loop will execute the code
block once, before checking if the condition is true, then it will repeat the loop as
long as the condition is true.
• int i = 0;
• do {
• cout << i << "\n";
• i++;
• }
• while (i < 5);
FOR LOOP

• When you know exactly how many times you want to loop through a
block of code, use the for loop instead of a while loop:
• Statement 1 is executed (one time) before the execution of the code block.

• Statement 2 defines the condition for executing the code block.

• Statement 3 is executed (every time) after the code block has been executed

• for (int i = 0; i < 5; i++) {

• cout << i << "\n";

• }
ARRAYS

• Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.

• To declare an array, define the variable type, specify the name of the array followed by
square brackets and specify the number of elements it should store:

• string cars[4];
• We have now declared a variable that holds an array of four strings. To insert values to it,
we can use an array literal - place the values in a comma-separated list, inside curly
braces:

• string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};


ACCESS THE ELEMENTS OF AN ARRAY

• You access an array element by referring to the index number inside


square brackets [].
• string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
• cout << cars[0];
Change an Array Element:
To change the value of a specific element, refer to the index number:
cars[0] = "Opel";
LOOP THROUGH AN ARRAY

• string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};

• for (int i = 0; i < 5; i++) { 1

• cout << cars[i] << "\n";

• }

• string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};

• for (int i = 0; i < 5; i++) {

• cout << i << " = " << cars[i] << "\n"; 2

• }

• int myNumbers[5] = {10, 20, 30, 40, 50};

• for (int i = 0; i < 5; i++) {

• cout << myNumbers[i] << "\n"; 3

• }
ARRAY SIZE

• To get the size of an array, you can use the sizeof() operator
• int myNumbers[5] = {10, 20, 30, 40, 50};
• cout << sizeof(myNumbers);

C++ Functions:
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
Functions are used to perform certain actions, and they are important for
reusing code: Define the code once, and use it many times
CREATE A FUNCTION

• C++ provides some pre-defined functions, such as main(), which is


used to execute code. But you can also create your own functions to
perform certain actions.
• To create (often referred to as declare) a function, specify the name of
the function, followed by parentheses ():
• void myfunction() {
• // code to be executed
• }
EXAMPLE

• myFunction() is the name of the function


• void means that the function does not have a return value. You will
learn more about return values later in the next chapter
• inside the function (the body), add code that defines what the function
should do
CALL A FUNCTION

• Declared functions are not executed immediately. They are "saved for
later use", and will be executed later, when they are called.

• To call a function, write the function's name followed by two


parentheses () and a semicolon ;

• In the following example, myFunction() is used to print a text (the


action), when it is called:
EXAMPLE

• // Create a function
• void myFunction() {
void myFunction() {
cout << "I just got executed!\n";
• cout << "I just got executed!";
}
• }
int main() {
• int main() { myFunction();
myFunction();
• myFunction(); // call the function
myFunction();
• return 0;
return 0;
• } }

• // Outputs "I just got executed!"


FUNCTION DECLARATION AND DEFINITION

• Declaration: the return type, the name of the function, and parameters (if any)
• Definition: the body of the function (code to be executed)

• // Function declaration
• void myFunction();

• // Function definition
• void myFunction() {
• cout << "I just got executed!";
• }
EXAMPLE

• // Function declaration

• void myFunction();

• // The main method

• int main() {

• myFunction(); // call the function

• return 0;

• }

• // Function definition

• void myFunction() {

• cout << "I just got executed!";

• }
PARAMETERS AND ARGUMENTS

• Information can be passed to functions as a parameter. Parameters act as variables inside the function.
• Parameters are specified after the function name, inside the parentheses. You can add as many
parameters as you want, just separate them with a comma:
• void myFunction(string fname) {
• cout << fname << " Refsnes\n";
• }
• int main() {
• myFunction("Liam");
• myFunction("Jenny");
• myFunction("Anja");
• return 0;
• }
C++ MULTIPLE PARAMETERS

• void myFunction(string fname, int age) {


• cout << fname << " Refsnes. " << age << " years old. \n";
• }

• int main() {
• myFunction("Liam", 3);
• myFunction("Jenny", 14);
• myFunction("Anja", 30);
• return 0;
• }
RETURN VALUES

• The void keyword, used in the previous examples, indicates that the function should not return
a value. If you want the function to return a value, you can use a data type (such as int, string,
etc.) instead of void, and use the return keyword inside the function:
• int myFunction(int x) {
• return 5 + x;
• }
• int main() {
• cout << myFunction(3);
• return 0;
• }
EXAMPLE

• int myFunction(int x, int y) {


• return x + y;
• }

• int main() {
• cout << myFunction(5, 3);
• return 0;
• }
?

You might also like