100% found this document useful (1 vote)
11 views22 pages

C++ RE-Exam Document

Chapter 1 introduces C++, a high-level programming language developed by Bjarne Stroustrup, emphasizing its features such as object-oriented programming, fast execution, and modularity. It covers basic concepts including programming languages, variables, user input, data types, and operators, as well as decision-making structures like if, else, and else if statements. The chapter provides examples and syntax to illustrate how to write and execute C++ code effectively.

Uploaded by

MAHER MOHAMED
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
11 views22 pages

C++ RE-Exam Document

Chapter 1 introduces C++, a high-level programming language developed by Bjarne Stroustrup, emphasizing its features such as object-oriented programming, fast execution, and modularity. It covers basic concepts including programming languages, variables, user input, data types, and operators, as well as decision-making structures like if, else, and else if statements. The chapter provides examples and syntax to illustrate how to write and execute C++ code effectively.

Uploaded by

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

Chapter 1

1. Introduction to C++

Program (Software)

❖ Set of instructions that tell computer what to do


❖ Program is a piece of code that performs specific task.
❖ We use programs to interact with computers.
❖ To write programs we use programming languages
Programming languages

❖ Programming languages are languages used to write programs.


❖ Computers are machines, they do not understand human languages.
❖ Programs are written in a language that computer can understand.
Machine Language

❖ A computer’s native language


❖ Uses zeros & ones (0 and 1) Binary Language.
❖ Every instruction should be written in machine language before it can be executed.
❖ All instructions written in other programming languages must be translated in machine
code instructions.

Assembly Language

❖ It was developed to make programming easier.

❖ Machine dependent.

❖ Introduced keywords (add, sub, -------------------- )

❖ Assembler translates assembly code into machine code.

High level Programming languages

❖ Are new generations of programming languages.

❖ Uses English words (Easy to learn and use)

❖ Program written in a high-level language is called source code or source program code.

1
1. Introduction to C++
C++ is a powerful, high-level programming language that supports both procedural and object-
oriented programming. It was developed by Bjarne Stroustrup as an extension of the C language.
C++ is widely used for developing system software, games, and applications due to its efficiency
and flexibility.
2. Key Features of C++
• Object-Oriented: Supports concepts like classes, objects, and inheritance.
• Fast Execution: Optimized for performance and speed.
• Modular Programming: Supports functions and reusable code.
• Platform Independent: Can be used on various operating systems.
• Rich Library Support: Includes the Standard Template Library (STL) for data structures
and algorithms.

What is 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 in 1979.
❖ C++ gives programmers a high level of control over system resources and memory.
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 portable and can be used to develop applications that can be adapted to multiple
platforms.
C++ Syntax

❖ Let's break up the following code to understand it better:


Example
#include <iostream>

using namespace std;

2
int main() {

cout << "Hello World!"; return 0; }

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 stdmeans 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.

3
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: Every C++ statement ends with a semicolon ;.


❖ Note: The body of int main()could also been written as:
int main () { cout << "Hello World! "; return 0; }
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.

C++ Output (Print Text)

The cout object, together with the <<operator, is used to output values/print text: Example
#include <iostream>
using namespace std;

int main() {

cout << "Hello World!";


return 0;

You can add as many coutobjects as you want. However, note that it does not insert a new line at
the end of the output:
C++ New Lines

To insert a new line, you can use the \ncharacter: Example


#include <iostream>
using namespace std;

int main() {

cout << "Hello World!n";

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

return 0; }

4
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;}

Both \nand endl are used to break lines. However, \nis used more often and is the preferred
way.
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 (//).

// This is a comment

C++ Multi-line Comments

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

/* The code below will print the words Hello World! to the screen, and it is amazing */

5
2. 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
❖ 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.

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:

6
Example

int myNum = 15; // myNum is 15

myNum = 10; // Now myNum is 10

cout << myNum; // Outputs 10

Display Variables

The coutobject 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.";

Declare Many Variables

To declare more than one variable of the same type, use a comma-separated list:
int x = 5, y = 6, 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:
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

7
3. 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:

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

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


In this example, the user must input two numbers. Then we print the sum by calculating (adding)
the two numbers: Example

int x, y; cin >> y;

int sum; sum = x + y;

cout << “Type a number: “; cout << “Sum is: “ << sum;

cin >> x; There you go! You just built a basic


calculator!
cout << “Type another number: “;

8
4. C++ Data Types

As explained in the Variables topic, 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

The data type specifies the size and type of information the variable will store

C++ Numeric Data 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 cout << myNum;

int myNum = 1000; double


cout << myNum; double myNum = 19.99;
float cout << myNum;
float myNum = 5.75;

9
C++ Boolean Data Types

A boolean data type is declared with the boolkeyword and can only take the values trueor
False. When the value is returned, true= 1and false= 0.
Example
bool isCodingFun = true;
bool isFishTasty = false;
cout << isCodingFun; // Outputs 1 (true)
cout << isFishTasty; // Outputs 0 (false)

C++ Character Data 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;

C++ String Data Types


Strings are used for storing text.
A stringvariable contains a collection of characters surrounded by double quotes:
Example
Create a variable of type stringand assign it a value:
string greeting = "Hello";
cout << greating;

C++ String Concatenation


The +operator can be used between strings to add them together to make a new string. This is
called concatenation: Example
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
cout << fullName;

10
C++ User Input Strings

It is possible to use the extraction operator >>on cinto display a string entered by a user:
Example
string firstName;
cout << "Type your first name: ";
cin >> firstName; // get user input from the keyboard
cout << "Your name is: " << firstName;
// Type your first name: John
// Your name is: John
However, cinconsiders a space (whitespace, tabs, etc) as a terminating character, which means
that it can only display a single word (even if you type many words):

5. 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:

11
Arithmetic operators

Arithmetic operators are used to perform common mathematical operations.

Example

Int x = 1000;
Int y = 1000;
cout << x + y;

Comparison operators

Comparison operators are used to compare two values.

Note: The return value of a comparison is either true (1) or false (0).

12
Example

Int x = 1000;
Int y = 2000;
cout << x > y; // returns 1 (true) because 2000 is greater than 1000

Assignment operators

Assignment operators are used to assign values to variables.

Example

Int x = 1000;
x += 1000;
cout << x;
Logical operators

Logical operators are used to determine the logic between variables or values:

13
Chapter 2 DECISION MAKING

1. Conditions
The if Statement
Use the ifstatement to specify a block of C++ code to be executed if a condition is true.
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
❖ Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.

In the example below, we test two values to find out if 20 is greater than 18. If the condition is
true, print some text:
Example
if (20 > 18) {
cout << "20 is greater than 18";
}
We can also test variables:
Example

int x = 20;

int y = 18;

if (x > y) {
cout << "x is greater than y";
}
Example explained

In the example above we use two variables, x and y, to test whether x is greater than y (using the
>operator). As x is 20, and y is 18, and we know that 20 is greater than 18, we print to the screen
that "x is greater than y".

14
The else Statement
Use the elsestatement to specify a block of code to be executed if the condition is false.
Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Example
int time = 20;
if (time < 18) {
cout << "Good day.";
}
else {
cout << "Good evening.";
}
// Outputs "Good evening."
Example explained
In the example above, time (20) is greater than 18, so the condition is false. Because of this, we
move on to the else condition and print to the screen "Good evening". If the time was less than
18, the program would print "Good day".

15
The Else If Statement
Use the else ifstatement to specify a new condition if the first condition is false.
Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
Example
int time = 22;
if (time < 10) {
cout << "Good morning.";
}
else if (time < 20) {
cout << "Good day.";
}
else {
cout << "Good evening.";
}
// Outputs "Good evening."

Example explained
In the example above, time (22) is greater than 10, so the first condition is false. The next
condition, in the else ifstatement, is also false, so we move on to the elsecondition since
condition1 and condition2 is both false- and print to the screen "Good evening".

However, if the time was 14, our program would print "Good day."

16
2. C++ Switch Statements
Use the switchstatement to select one of many code blocks to be executed.
Syntax switch(expression) { case x:
// code block
break; case y:
// code block break; default:
// code block
}
This is how it works:
❖ The switchexpression is evaluated once
❖ The value of the expression is compared with the values of each case
❖ If there is a match, the associated block of code is executed
❖ The breakand defaultkeywords are optional
The example below uses the weekday number to calculate the weekday name:
Example
int day = 4; switch (day) { case 1:

cout << "Monday"; break;

case 2:

cout << "Tuesday"; break;

case 3:

cout << "Wednesday"; break;

case 4:

cout << "Thursday"; break;

// Outputs "Thursday" (day 4)

17
The 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.
A break can save a lot of execution time because it "ignores" the execution of all the rest of the
code in the switch block.
The default Keyword
The defaultkeyword specifies some code to run if there is no case match:
Example
int day = 4;
switch (day) {
case 6:
cout << "Today is Saturday"; break;
case 7:
cout << "Today is Sunday"; break;
default:
cout << "Looking forward to the Weekend";
}
// Outputs "Looking forward to the Weekend"

Note: The default keyword must be used as the last statement in the switch, and it does not need
a break.

18
Chapter Three: - Loops, Arrays and Functions

C++ Loops
➢ Often when you write code, you want the same block of code to run over and over again
in a row. Instead of adding several almost equal code-lines in a script, we can use
loops to perform a task like this.
➢ In C++, we have the following looping statements:
➢ while - loops through a block of code as long as the specified condition is true
➢ do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
➢ for - loops through a block of code a specified number of times
The C++ while Loop
➢ The while loop executes a block of code as long as the specified condition is true.
Syntax
➢ while (condition) {
// code block to be executed
}
Example
int i = 0;
while (i < 5) {
cout << i << "\n";
i++; }
The C++ 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.
Syntax do {
// code block to be executed
}
while (condition);
Example
➢ int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5);
The C++ 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:

19
Syntax
➢ for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Example
for (int i = 0; i < 5; i++) {
cout << i << "\n";
}

C++ 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 [].

20
b) Functions in C++
A function is a block of code that performs a specific task. Functions help in breaking down a
program into smaller, reusable components. Example:
#include <iostream>
using namespace std;

void greet() {
cout << "Hello, Welcome to C++!";
}

int main() {
greet();
return 0;
}

5. Object-Oriented Programming (OOP) in C++


C++ supports Object-Oriented Programming, which includes:
• Encapsulation: Hiding data using private and public access modifiers.
• Inheritance: Creating new classes from existing ones.
• Polymorphism: Using functions in multiple ways.
• Abstraction: Hiding implementation details from the user.
6. Classes and Objects in C++
A class is a blueprint for creating objects, while an object is an instance of a class. Example:
#include <iostream>
using namespace std;

class Car {
public:
string brand;
void display() {
cout << "Brand: " << brand;
21
}
};

int main() {
Car myCar;
myCar.brand = "Toyota";
myCar.display();
return 0;
}
7. Comparison of C and C++
Feature C Language C++ Language
Programming Paradigm Procedural Object-Oriented + Procedural
Data Security Less secure More secure (Encapsulation)
Function Overloading Not supported Supported
Standard Input/Output scanf(), printf() cin, cout
8. Importance of C++ in Modern Programming
C++ is widely used in developing:
• Operating systems (e.g., Windows, Linux)
• Game engines (e.g., Unreal Engine)
• Web browsers (e.g., Google Chrome, Mozilla Firefox)
• Financial applications and databases
Conclusion
C++ is a fundamental programming language that provides a strong foundation for software
development. Learning C++ helps in understanding core programming concepts and prepares
developers for advanced programming challenges.

22

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy