Uploaded by abdiendale25

C lang

advertisement
2
2ND SEMISTER CONTENT OF ICT SUBJECT
I am Teacher of AIBSBS in 2023
My Email Address:
bilisumasori430@gmail.com
Learning Outcomes
3
The students will able to:
Understand the how a computer understands instructions.
 Computer programing.
 Concepts of Algorithms and Characteristics.
 Draw Flowcharts and their symbols.
 The difference between Algorithms and Flowcharts.
 Programming Languages and Translators.
 The difference between Compiler and Interpreter.
 Pseudocodes.
 Fundamental concept of programming languages.

Chapter Five: Computer Programming?
4
What is computer Programming?
Computer programming is the process of creating computer
programs.
 A program is a set instructions that tell a computer what to do.
 A program is created using a programming Language.
 If any program is designed for end user to perform a specific
task or achieve a specific Purpose is called an Application.
 Applications are often created with a user interface that allows
users to interact with the program, providing input and receiving
output.
 Examples of Applications: Word Processor, Spreadsheets, Web
browsers, and Media players.

Chapter Five: Computer Programming?
5




All applications are programs but not all programs are
applications.
For example: There are thousands of programs running in
the background of your operating system such as
programs that manage network connections, since they are
not develop for the end user, they are not applications.
The term Software also gets confused with the terms
program and application.
You will encounter people saying a video player software,
a document processing software, or an OS software.
Chapter Five: Computer Programming?
6





Software is an all-encompassing term that is used to describe any
part of a computer that is not tangible (Hardware).
All programs and applications are types of software.
But for a computer to run certain instructions, the instructions must be
first given by a human being.
Without a set of instructions, a computer has nothing to do. As you
remember in previous chapters computer understands only ones and
zeroes.
People used to write different programs by using ones and Zeroes.
But as these instruction grow, it becomes very difficult to successfully
write, read and debug them. So, People created two major things.
Chapter Five: Computer Programming?
7
1. A human- readable language to write the instructions and
2. A program that changes these human- readable instructions to a
machine code.
These human-readable languages are called Programming Languages.
Coding and Coder: A technical person who uses a particular programming language to
implement the program logic is called a coder.
 The act of this technical person is called Coding. But before coding
the logic must be created by using critical thinking skills and solving
logical problems.
 The creation of logic and the process of developing fully functioning
Software is called Programming. Coding is a part of programming.
Chapter Five: Computer Programming?
8





Programming is a broader term that encompasses the entire
process of designing, writing, testing, and maintaining computer
programs.
Programming involves not only writing code, but also designing and
testing the code, and maintaining the software over time.
The individual who does the act of programming is called a
programmer.
A computer programmer is sometimes referred to as Software
Developer, Software Engineer, and application Developer.
Computer Programmers write a set of instruction or steps used to
solve a problem or perform a specific task, which are called
Algorithms.
Chapter Five: Computer Programming?
9
The applications in our devices you use in The quality an algorithm depends
your daily life Algorithms.
on several factors such as:



Navigation
 To using GPS to find Address.
Social Media
 It uses various algorithms to
personalize your feed by showing
you posts.
Online Shopping
 Purchases Product.


Accuracy
Efficiency

Simplicity

Scalability

Robustness
Note:- Different people may use different algorithms to solve the same problem.
Solving the same problem efficiently with lower time and resource makes
algorithms better and efficient.
Chapter Five : Computer Programming?
10
Sample Example algorithms are used in many aspects of our daily
lives, often without even realizing it.
1. Write an algorithm to log in to your Facebook account.
Remember:- An algorithm is a step by step procedure to solve a given
problem.
Answer: In simple English
Open Operamini
 Go to WWW.Facebook.com
 Enter Email ID and Password
 Click on log in button

2. How will you log in to your Facebook account?
Answer:- Using laptop, tablet, using friends computer, From internet Café,
Smartphone, College campus and much more may be your may answer.
Chapter Five : Computer Programming?
11
Definition of Algorithms:It is a process or Step by step instructions for solving a problem.
 They form the foundation of writing a program.
 It is a finite steps to solve a program.
 It is a set of rules to solve problems.
 There is no standard rule to writing algorithm.

Examples: 1 Write an algorithm of adding 3 numbers.
Step 1: Start
Step 2: Read num1, num2, num3
Step 3: Sum = num1 + num2 + num3
Step 4: Print Result
Step 5: Stop
Chapter Five : Computer Programming?
12
Examples: 2. Write an algorithm to find the greater of two numbers
Step 1: Start
Step 2: Declare a, b
Step 3: Read Variables a, b
Step 4: If a > b
1. Yes, Print a
2. No, print b
Step 5: Stop
Examples: 3. Write an algorithm to calculate an area of a triangle
Step 1: Start
Step 2: Declare the variables
Step 3: Area of Triangle
Step 4: Print Area
Step 5: Stop
Chapter Five : Computer Programming?
13
Advantages of Algorithm:
You can easily understand the motive of the program
 Helps in searching || identifying the error
 Helps in correcting the error
 Helps to write a complex program in an easy way as because
algorithm solves any problem || Program step-by-step

Properties of Algorithm:
It should terminate after a finite time.
 It should produce at least one output.
 It should take zero or more input.
 It should be deterministic means giving the same output for the
same input case.
 Every step in the algorithm must be effective i.e. every step
should do some work.

Chapter Five : Computer Programming?
14
Characteristics of Algorithm






Input :- An algorithm has zero or more well defined inputs.
Output: An algorithm produces at least one output.
Clear and Unambiguous: The algorithm should be clear and
unambiguous.
 Every instruction must be clear and precise is should be not
ambiguous.
Finiteness :- The algorithm must be finite (it should terminate after a
finite time).
Effectiveness:- An algorithm must be developed by using very
basic, simple, and feasible operations
Definiteness: All instructions in an algorithm must be unambiguous,
precise, and easy to interpret.
Chapter Five : Computer Programming?
15
What is Flow charts?
A flowcharts is a visual representation of a process or algorithm
that uses symbols, arrows, and other graphical elements to
show the flow of control and the sequence of steps involved in
the process.
 Flowcharts consists of a series of interconnected shapes or
symbols, each of which represents a specific step in the process.
 The shapes may include rectangles for process, diamond for
decision points, Ovals for starting may and ending points, and
other Symbols to represent specific operations or data inputs
and outputs.

Chapter Five : Computer Programming?
16
There are five basic symbols commonly used in flowcharts.
These are:-
Chapter Five : Computer Programming?
17
The Rules For writing flowchart
Flowchart should be drawn using certain symbols.
 The flow of the flowchart should be shown with an arrow pointing
from top to bottom or from left to right
 Each flowchart must have one and only one start object
 The flow of control must always enter an object from the top
 The use of additional symbols should be avoided
 The writing inside each symbol should be easy to understand
 Flowchart is easier to read and understand.
 They must start and end with the Terminal or Process Symbol.
 A Decision must have 2 exit points. One for True and another for
False
 All boxes of flowcharts must be connected with Control flow
arrows.

Chapter Five : Computer Programming?
18
Consider the following points while drawing a flowchart.
 Start with clear goal.
 Use the standard symbols consistently to avoid Confusion.
 Use clear and concise language.
 Keep it simple:- Flowcharts should be easy to read.
 Test the flowchart:- Test it to make sure.
Note:- The above rules and considerations can help you create
effective and accurate flowcharts that accurately represent
the process or algorithm you are trying to describe.
Chapter Five : Computer Programming?
19
Examples for Flowcharts and Algorithms:

Graphical representation of algorithm or a types of diagram that
represents an algorithm or process.
Examples: 1 Write an algorithm and flowchart of addition of three numbers
Algorithm
Step 1: Start
Step 2: Read 3 variables
Step 3: Sum: = A+B+C
Step 4: Print Sum
Step 5: Stop
Flowchart
Start
Read A B C
SUM = A + B + C
Print Sum
Stop
Chapter Five : Computer Programming?
20
Example:-2
Write an algorithm and flowchart to find the area of a triangle
Algorithm
Step 1: Start
Step 2: Read base, height
Step 3: Area = ½ (base * Height)
Step 4: Print Area
Step 5: Stop
Hint: Base is represent “b” and
Height is represent “h”.
Flowchart
Start
Read b, h
Area = ½ (b * h )
Print Area
Stop
Chapter Five : Computer Programming?
21
Example:- 3 Write an algorithm and flowchart to check whether a number is even or odd.
Flowchart
Algorithm
Start
Step 1: Start
Step 2: Enter Number
Step 3: Check if Number
Enter Number
N %2
== 0
TRUE
Even
FALSE
Odd
Stop
Modulus 2 == 0
Print Even
Step 4: Otherwise odd
Step 5: Stop
Chapter Five : Computer Programming?
22
The Difference between Flowchart and Algorithm
Flowchart
 Flowchart is used to
design some symbols.
 It is more consuming.
 Difficult to modify
 It is a graphical
representation of solution.
 In flowchart difficult to
debug errors.
Algorithm
 Algorithm is used to write
simple English language.
 It is less time consuming.
 Easy to modify
 It is step by step
description of solution.
 But in algorithm easy to
debug errors.
Chapter Five: Computer Programming?
23
What is Pseudo code (False code)?







Pseudo is from the Greek “Psevdes”, Meaning False.
Pseudocode is not an actual Programming language.
Pseudocode is step by step written outline of your code that you
can gradually transcribe into the Programming language.
Pseudocode is written in Plain English-statement.
There is no standard syntax for pseudocode, as it is not a formal
programming language.
Pseudocode is a method of describing computer algorithms using a
combination of natural language and programming language
constructs.
Pseudocode does not run on a computer.
Chapter Five: Computer Programming?
24
Write simple pseudocode example to add two numbers
BEGIN
NUMBER num1, num2, sum
OUTPUT ("Input number1:")
INPUT num1
OUTPUT ("Input number2:")
INPUT num2
sum = num1+num2
OUTPUT sum
END
This pseudocode describes a program that
takes two numbers as input from the user,
adds them together and outputs the sum.
1. The variables “num1”, “num2”, and “sum” are
declared.
2. The program outputs the message “Input
number1:” and waits for the user to
input a value, which is stored in “num1”.
3. The program outputs the message “Input
number2:” and waits for the user to
input a value, which is stored in “num2”.
4. The value of “sum” is calculated as the
sum of “num1” and “num2”.
5. The value of “sum” is outputted as the
result of the program.
Chapter Five: Computer Programming?
25
Find Area Of Circle using Radius (Simple Pseudocode Example)
BEGIN
NUMBER r, area of circle
INPUT r
area of Circle =3.14*r*r
OUTPUT area of circle
END
This pseudocode describes a program that
calculates the area of a circle given its radius.
===========================
1. The variables “r” and “area” are declared.
2. The program prompts the user to input the
radius of the circle and stores the value in “r”.
3. The area of the circle is calculated by
multiplying pi (3.14) by the square of the
radius and storing the result in the “area”
variable.
4. The program outputs the value stored
in the “area” variable.
==============================
Chapter Five: Computer Programming?
26
Shell
Find the Pseudocode of the biggest of three (3) Numbers.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
BEGIN
NUMBER num1,num2,num3
INPUT num1
INPUT num2
INPUT num3
IF num1>num2 AND
num1>num3 THEN
OUTPUT num1+ "is higher"
ELSE IF num2 > num3 THEN
OUTPUT num2 + "is higher"
ELSE
OUTPUT num3+ "is higher"
ENDIF
END
This pseudocode describes a program that determines
the highest of three numbers entered by the user.
1. The variables “num1”, “num2”, and “num3” are
declared.
2. The program prompts the user to enter three
numbers and stores the values in “num1”, “num2”,
and “num3”.
3. The program checks if “num1” is greater than both
“num2” and “num3”.
4. If “num1” is greater than both “num2” and “num3”,
the program outputs the message “num1 is higher”.
5. If “num1” is not greater than both “num2” and “num3”, the
program checks if “num2” is greater than “num3”.
6. If “num2” is greater than “num3”, the program
outputs the message “num2 is higher”.
7. If “num2” is not greater than “num3”, the program
outputs the message “num3 is higher”.
Chapter Five : Computer Programming?
27
The Difference between Algorithm and Pseudocode
Algorithm




An algorithm is a step-by-step
procedure developed to solve a
problem.
It can be understood as the
pseudocode for a program.
There are no rules to follow
while constructing it.
The selection of an algorithm
depends upon the nature of the
given problem.
Pseudocode (False Code)





A pseudocode is a technique of
developing an algorithm.
A pseudocode is an informal
language to write algorithms.
Pseudocode is not actually a
programming language.
It has certain rules to follow while
constructing it.
The pseudocode is a text based
design tool.
Note: Pseudocode is an intermediary between an algorithm and implemented program.
Chapter Five: Computer Programming?
28
What is Programming Language?
A program is created using a programming Language.
 A programming language is a language that can be used to
communicate with a computer.
 A programming language is a computer language that is used by
programmers (developers) to communicate with computers.
 Therefore a programming language is the equivalent of a
language such as English when it comes to communication with
computers.
 There are several programming languages in existence today.
The most Common Programming Languages are divided into:

 Assembly
Languages && Machine Languages
 Low level Language && High Level Languages
Chapter Five: Computer Programming?
29
The most Common Programming Languages are:

Python: (Animation and Game Programming).


it can also be used for general purpose programming.
Java: (General purpose programming).

Most common Programming language Object Oriented Programming.
C - (Low level, Structural Programming).
 C++ - (High/Low level, Object Oriented Programming).
 CSS (Web design and Styling).
 Html (Web development and design).
 JavaScript (Mainly web development).

 Also
used for general purpose programming and Game development).
Chapter Five: Computer Programming?
30
Low level and high level programming Language

Low level language
 It
is Programming languages that designed to interact directly with a
computers' hardware and is closer to machine code.
 They provide little to no abstraction from the hardware.
 Examples of low level languages


Machines Language and Assembly language
High Level Language
It programming languages that are designed to be more abstract and
easier to read, write, and understand than low-level languages.
 They allow a programmer to use English-like words to create programs
that are not dependent on the type of computer they are running on.
 Examples of High level Languages:


Python, Java, Visual Basic, C++ ,etc
Chapter Five: Computer Programming?
31
To convert high-level or intermediate-level language source codes to
an executable machine code (that can be run on a computer), two
types of special programs are needed.
Two Special programs are:1. Compiler:- It takes the whole source code and transforms it into
an executable machine code.
 Programming Languages who compile themselves into machine
code before execution are called Compiled Languages.
Note:- A compiler is a complex piece of software whose jobs
in to convert source code to machine understandable code
(binary code) in one go.
Chapter Five: Computer Programming?
32
2. Interpreter:- It takes the source code line by line and then
converts it to a machine code when the program is run.
The interpreter reads each line of code, interprets its meaning,
and executes the corresponding instructions on the fly.
 Interpreters are commonly used in programming languages
likes Python, JavaScript, and PHP.
Note:- An interpreter is a software program written to translate
source code to machine code but it does that line by line

Chapter Five : Computer Programming?
33
The Difference between Compiler and Interpreter
Compiler






It Scans the entire programs first and
translates in into machine code.
Compiler show all errors and running
at the same time
Error occurs after scanning the
whole program.
Debugging is slow.
Execution time is less.
Compiler is used by languages such
as C, C++ and etc
Interpreter

It scans the program line by line and
translate it into machine code.
Interpreter show one error at the a
time.
Error occurs after Scanning each line.
Debugging is faster.
Execution time is more

An interpreter is used by languages




such as PHP, Java, Python and etc.
Chapter Five: Computer Programming?
34
Advantages of using compilers
Faster Execution speed
 Better memory management, as compiled code can be optimized
for specific hardware and operating system.
 It can generate standalone executable files that can be
distributed to other computers without requiring the source code
or an interpreter.
Advantages of using interpreters
 Easier to write and debug, as errors can be identified and
corrected in real-time.
 More portable, as the same code can run on different platforms
without requiring recompilation.
 Very beginner friendly.

Chapter Five: Computer Programming?
35
Intermediate – level languages
 To
provide a compromise between the low-level control and
efficiency of assembly language and the ease of use and
higher-level abstraction of high-level languages like Python
or Java.
 Examples of Intermediate-level programming languages are
C, C++, Rust.
Note:- The distinction between programming language levels is not
always clear-cut and some languages can be categorized in
different ways depending on how they are used.
Chapter Five : Computer Programming?
36
Any text editor like Notepad can be used for writing Source code.
 But it is very recommended to use an Integrated Development
Environment (IDEs).
Note: IDEs offer necessary tools and different features to
your code like: Autocomplete:- It will guess what you want to write.
 Syntax Highlight:- It colors different parts of the code for better
visualization.
 Build Automation:- They make it easy to directly run the
program without any configuration and much more.

Chapter Five : Computer Programming?
37
Most programming Languages have their own IDEs.
For Example:1. Dev-C++ is a free full-featured Ide to build C and C++.
2. Android Studio: It Provides almost everything you need to build an android
application by using Java.
3. PHP Storm: It provides different tools to build apps with PHP.
There are also general-purpose code Editors that support many Programming languages at
once. like Sublime Text and Visual Studio Code.
What is source code and Source File?
Source code (A complete code of program) is
looking at source from the inside, like a
programmer.
Source file (A file that contains program
instructions) is looking at source from the outside,
like a manager or lawyer.
Chapter Five : Computer Programming?
38
HOME WORK (10% Marks)
1. Write an algorithm and flowchart to find the area of a Rectangle.
2. Write an algorithm and flowchart to find the Smallest number
between 2 whole numbers.
3. Write an algorithm and flowchart to find the area of a circle.
4. Write an algorithm and flowchart to determine the factorial of a
positive whole number.
5. Write an algorithm and flowchart that converts temperature from
Fahrenheit to centigrade (Celsius).
6. Write an algorithm and flowchart to find the average of two
numbers.
39
Chapter Five : Computer Programming?
40
Chapter Six : Programming with C++
C ++
Learning Outlines
41
Students will be able to:








Very brief history of C++ Programming Language.
Understand the fundamental concepts of the C++ Programming
Language.
Able to understand the complication process of the C++
Programming Language.
Able to write Statement that executes based on given condition.
Able to write programs that can take inputs and return outputs.
Able to use different control flow statements.
Able to familiarize and work with functions.
Understand the concept behind pointers and use them properly.
Chapter Six : Programming with C++
42
Very brief history of C++
C++
For details more check out A History of C++: 1979−1991
Chapter Six : Programming with C++
43
Introduction of C++ Programming

C++ is a powerful language.

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 language was updated 4 major times in 2011, 2014, 2017 and 2020 to C++11,
C++14, C++17 and C++20.
Why Use C++?
 C++ is one of the world’s most popular programming languages.
 C++ can be found in today’s OS, GUIs, and embedded systems.
 C++ is an object-oriented programming language that 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!
 C++ is a superset of C and therefore most constructs of C are legal in C++ with their
meaning unchanged. However, there are some exceptions and additions.

Chapter Six : Programming with C++
44
C++ Basic Program
// C++ “Hello World” Program
#include <iostream>
using namespace std;
The main routine – the start of every C++ program!
int main()
It returns an integer value to the operating system
and (in this case) takes no arguments: main()
{
cout << "Hello World!\n"; The return statement returns an integer value to the
operating system after completion. 0 means “no error”.
return 0;
C++ programs must return an integer value.
}
Chapter Six : Programming with C++
45
C++ Basic Program
loads a header file containing function
and class definitions
// C++ Hello World Program
Loads a namespace called std. Namespaces are used
#include <iostream>
to separate sections of code for programmer
using namespace std;
convenience. In C++, a namespace is a collection of
related names or identifiers (functions, class, variables)
int main()
which helps to separate these identifiers from similar
{
identifiers in other namespaces
cout << “Hello World!\n” << endl;
 cout is the object that writes to the stdout device, i.e. the
return 0;
console window. Cout is send message to the screen.
}
 It is part of the C++ standard library.



Without the “using namespace std;” line this would have been
called as std::cout. It is defined in the iostream header file.
<< is the C++ insertion operator. It is used to pass characters
from the right to the object on the left.
endl is the C++ newline character.
Chapter Six : Programming with C++
46
Components of a C++ Code:
1. Comments:
The two slash (//) signs are used to add comments in a program.
 It does not have any effect on the behavior or outcome of the
program.
 It is used to give a description of the program you’re writing.

2. #include<iostream>:
#include is the pre-processor directive that is used to include files
in our program.
 Here we are including the iostream standard file which is
necessary for the declarations of basic standard input/output
library in C++.
 It is a header file library that lets us work with input and output
objects, such as cin and cout.

Chapter Six : Programming with C++
47
Components of a C++ Code:
3. Using namespace std:
All elements of the standard C++ library are declared within a
namespace. It means that we can use names for objects and
variables from the standard library.
 Namespaces are used to arrange code into logical categories
and to avoid name clashes, which might happen when you have
many libraries in your code base.

4. int main():
The execution of any C++ program starts with the main function.
 ‘int’ is the return value of a function.


The body of int main () could also been written as:
int main () { cout << "Hello World! "; return 0; }
Chapter Six : Programming with C++
48
Components of a C++ Code:
5. { and }


The curly brackets are used to indicate the starting and ending point
of any function.
Every opening bracket should have a corresponding closing bracket.
6. cout << “Hello World!\n”;
 It is an object used together with the insertion operator (<<) to
output/print text. In our example it will output "Hello World!".




cout represents the standard output stream in C++.
It is declared in the iostream standard file within the std namespace.
The text between quotations will be printed on the screen.
\n will not be printed, it is used to add a line break.
Note: Every C++ statement ends with a semicolon ; .
Chapter Six : Programming with C++
49
Components of a C++ Code:
7. return 0;
return signifies the ends the main function.
 The statement is the “Exit status” of the program.
 In simple terms, the program ends with this statement.
 We are returning 0 because we mentioned the return type of the
main function as integer (int main).
 A zero indicates that everything went fine and one indicates that
something has gone wrong.
Note that every statement ends with a semicolon (except
preprocessor commands and blocks using { } ). Forgetting these
semicolons is a common mistake among new C++ programmers.

You might see some C++ programs that runs without the standard namespace library. The using namespace std line can be omi
Chapter Six : Programming with C++
50
Basic Input / Output in C++
 C++ comes with libraries that provide us with many ways for
performing input and output.
 In C++ input and output are performed in the form of a sequence
of bytes or more commonly known as streams.


Input Stream: If the direction of flow of bytes is from the device (for example,
Keyboard) to the main memory then this process is called input.
Output Stream: If the direction of flow of bytes is opposite, i.e. from main
memory to device ( display screen ) then this process is called output.
Header files available in C++ for Input/Output operations are:



iostream: iostream stands for standard input-output stream.
This header file contains definitions of objects like cin, cout and etc.
The primary purpose of a header file is to propagate declarations to
code files.
You might see some C++ programs that runs without the standard namespace library. The using namespace std line can be omi
Chapter Six : Programming with C++
51
Key insight





Header files allow us to put declarations in one location and
then import them wherever we need them.
This can save a lot of typing in multi-file programs.
When you #include a file, the content of the included file is
inserted at the point of inclusion. This provides a useful way to
pull in declarations from another file.
In C++ after the header files, we often use ‘using namespace std;’.
The reason behind it is that all of the standard library definitions
are inside the namespace std.
As the library functions are not defined at global scope, so in order
to use them we use namespace std. So, that we don’t need to write
STD:: at every line (eg. STD::cout etc.).
You might see some C++ programs that runs without the standard namespace library. The using namespace std line can be omi
Chapter Six : Programming with C++
52
Omitting Namespace:

The using namespace std line can be omitted and replaced with
the std keyword, followed by the :: operator for some objects:
#include <iostream>
int main ()
{
std::cout << “Hello World!” <<std::endl;
return 0;
}
Note: It is up to you if you want to include the standard namespace
library or not.
A namespace is a declarative region that provides a scope to the
identifiers (the names of types, functions, variables, etc) inside it.
Namespaces are used to organize code into logical groups and to prevent
name collisions that can occur especially when your code base includes
multiple libraries.
Chapter Six : Programming with C++
53
Summary
 Any programs that print to the screen must use the #include
directive to so that the program can make use of the precompiled
iostream library code to do I/O (input and output).
 All preprocessor directives begin with the # symbol.
 Messages can be printed on the screen by sending them to the
std::cout object using the << operator.
 The << operator used in conjunction with the cout stream object
is known as the insertion operator.
 The end of a printed line is signified by sending std::endl to the
std::cout object.
 The shorter names cout and endl can be used if the using
namespace std appears at the top of the program’s source code.
Chapter Six : Programming with C++
54
Summary
 An executable C++ program must contain a function named
main.
 Functions contain statements that are executed by the computer
when the program runs. (The program must be compiled for the
computer to be able to execute the statements.)
 A function’s body consists of all the statements inside the
delimiting curly braces ({ }).
 A function’s body may be empty; however, such a function
performs no useful activity when it executes.
 Statements are terminated with semicolons (;).
 In a printing statement the characters within the quotation
marks (") are printed literally on the screen.
Chapter Six : Programming with C++
55
Comments in C++ Program
 Comments
are program text that is ignored by the Compiler.
 Comments help the human readers of our programs.
 They are typically used to summarize an algorithm, identify
the purpose of a variable, or clarify an otherwise obscure
segment of code.
 The compiler ignores comments, so they have no effect on the
program’s behavior or performance.
For whom are comments?
 Compiler  Ignores comments.
 Readers of our code  Makes use of comments to
understand the working of the code.
Chapter Six : Programming with C++
56
How to write comments in C++?
There are 2 types of comments in C++:1. //  Single- Line Comment.
2. /* Paried * /  Multiple-Line Comment.
In Single or multi-line comments: It is up to you which you want to use.
 Normally, we use // for short comments.
 And /* */ for longer.
Chapter Six : Programming with C++
57
How to write comments in C++?
Single-line:
A single-line comment starts with a double slash (//) and ends with a newline.
 Everything to the right of the slashes on the current line is ignored by the
compiler.
Example: This example uses a single-line comment before a line of code:

Example: This example uses a single-line comment at the end of a line of code:
Any text between // and the end of the line is ignored by the compiler (will not be executed).
Chapter Six : Programming with C++
58
How to write comments in C++?
2. /* Paried * /  Multiple-Line.
 It uses two delimiters (/* and */).
 It begin with a /* and end with the next */.
 These comments can include anything that is not a */, including newlines.
 The compiler treats everything that falls between the /* and */ as part of the
comment.
#include <iostream>
Using Namespace std;
Int main () {
Cout << “ Let’s Learn paired comments.”;
/* This is paired type comment.
Everything between the delimiters are ignored.
cout << “This too”; */
Return o;
}
Chapter Six : Programming with C++
59
Comments Pairs Do Not Nest in C++?
 A comment that begins with /* ends with the next */.
 As a result, one comment pair cannot appear inside
another. #include <iostream>
Using namespace std;
Example: Int main () {
Cout << “Let’s Learn Paired comments.”;
/* This is paired type comment.
Everything between the delimiters are ignored.
/*Another paired comment*/
Cout << “This too”; */
Return 0;
}
Chapter Six : Programming with C++
60
Keyword in C++ Program



Keywords are the reserved keywords that are defined by the
compiler to perform the internal operation, written in lowercase.
Keywords have some meaning which is defined by the compiler to
accomplish a task in code, they cannot be used as a variable in
programming.
C++ provides 64 keywords.
List of C++ Keywords
for, break, continue, switch, int, float, double, char, try, catch, while, auto, struct, else, long, case,
enum, register, typedef, extern, return, union, const, short, unsigned, continue, signed, void,
default, goto, sizeof, volatile, do, if, static, asm, dynamic_cast, namespace, reinterpret_cast,
bool, explicit, new, static_cast, catch false, operator, template, class, friend, private, this,
const_cast, inline, public, throw, delete, mutable, protected, true, typeid, typename, using, virtual,
wchar_t and etc.
Chapter Six : Programming with C++
61
C ++ Variables:

In C++, all the variables must be declared before use.
 Variables are containers for storing data values.

A variable provides us with named storage that our programs can manipulate.

Each variable in C++ has a type determines:



The size and layout of the variable’s memory.
The range of values that can be stored within that memory.
The set of operations that can be applied to the variable.
Variables Definitions
A simple variable definition consists of:A type specifier, followed by a list of one or more variable names separated by
commas, and ends with a semicolon.
Examples: int num1 ;
float num2, num3 ;
int num4 = 1; // initialization variable
int num5, num6 = 2 ; // initialization variable

Chapter Six : Programming with C++
62
Summary of C ++ Variables:








Variables are used to store values.
All variables in C++ must be declared before they are used
within the program.
A variable can be reassigned at any time.
A variable can be given an initial value at the time of its
declaration.
Multiple variables can be declared in one declaration statement.
A variable represents a location in memory capable of storing a
value.
A variable name is an example of an identifier.
The name of a variable must follow the identifier naming rules.
Chapter Six : Programming with C++
63
In C++, there are different types of variables (defined with different keywords).
int - stores integers (whole numbers), without decimals.
 such as 1234 or -1234
 double - stores floating point numbers, with decimals.
 For example :-such as 29.99 or -29.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
 Void - The void data type always represents an empty set of values.

 it
indicates that the function does not return a value.
Chapter Six : Programming with C++
64
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
For Example:
Create a variable called myNum of type int and assign it the value 16:
int myNum = 16;
cout << myNum;
Note that if you assign a new value to an existing variable, it will overwrite the
previous value:
int myNum = 16; // myNum is 16
myNum = 12; // Now myNum is 12
cout << myNum; // Outputs 12
Chapter Six : Programming with C++
65
What is the identifier?
Identifiers in C++ can be composed of letters, digits, and
the underscore character.
 Identifiers are the unique names given to variables,
classes, functions, or other entities by the programmer.
 They are the fundamental requirement of any language.
 Identifiers:- sequence of characters that make up a name.

Examples: int a1; int A1; and float _b3;
Note: All identifiers must consist of at least one character. The first
symbol must be an alphabetic letter or the underscore. Remaining
symbols (if any) must be alphabetic letters, the underscore, or digits.
Chapter Six : Programming with C++
66
Rules for identifiers:








Identifiers must begin with either a letter or an underscore (_).
Identifiers are Case-sensitive; The upper case and lower case
letters are distinct. i.e., A and a are different in C++.
Identifier names can not start with a digit.
Identifier names cannot contain whitespaces or special characters
like !, #, %, etc.
There are no restrictions on the length of a name.
C++ keywords are significant and cannot be used as names.
The language imposes no limit on name length.
The language reserves a set of names, for its own use. These
names may not be used as identifiers.
67
Keyword






Keywords are predefined/reserved
words.
Keywords always start in lowercase.
It defines the type of entity.
A keyword contains only alphabetical
characters,
It should be lowercase.
Keywords: int, char, while, do.
Identifier

identifiers are the values used to define
different programming items like a
variable, integers, structures, and unions.
identifiers can start with an uppercase
letter as well as a lowercase letter.
It classifies the name of the entity.
an identifier can consist of alphabetical
characters, digits, and underscores.
It can be both upper and lowercase.

Identifiers: Geeks_for_Geeks, GFG, Gfg1.




Note:- No special symbols or punctuations are used in keywords
and identifiers. The only underscore can be used in an identifier.
Chapter Six : Programming with C++
68
C++ Data Types
Example:
Basic Data Types:
The data type specifies the size and type of information the variable will store:
Chapter Six : Programming with C++
69
Type conversion in C++ program
The conversion of a variable from one data type to another is called
Type Conversion in C++.
 Type conversion in C++ is most commonly used to perform
mathematical and logical operations on two variables with
different data types.
 Using type conversion, we change the data type of one variable to
become compatible with the other variable.
For example, while calculating the sum of two numbers - where one
number is a floating-point number, and the other is an integer, we
convert the integer to a floating-point number to operate correctly.
Note:- Changing the data type of a variable is called type conversion.

70
Types of conversion in C++ - Implicit and Explicit.





It is done automatically by the compiler.
It does not require any effort from the programmer.
The online C++ compiler has a set of predefined rules.
The compiler automatically converts one data type to
another based on these rules.
it is automatic type conversion.
Chapter Six : Programming with C++
71
Types of conversion in C++ - Implicit and Explicit.
Implicit type conversion - Data Loss During Conversion.




When there is more than one data type present in an expression,
there is a possibility of data loss because different data types are
incompatible.
Data loss occurs if a variable converts from a higher data type to a
lower data type.
To avoid data loss, the compiler automatically converts all the data
types to the highest data type present in the expression.
This is called promotion. The precedence of different data types is
given below.
Chapter Six : Programming with C++
72
Types of conversion in C++ - Implicit and Explicit.
Chapter Six : Programming with C++
73
Types of conversion in C++ - Implicit and Explicit.
Explicit type conversion
It is done by the programmer manually.
 It allows the programmer to typecast (change) the data
type of a variable to another type.
 Generally, we use the explicit type conversion if we do not
want to follow the implicit type conversion rules.
Explicit type conversion in C++ can be done in two ways:

1.
2.
Conversion using the Assignment Operator or the cast
operator.
Conversion using the Cast Operator
Chapter Six : Programming with C++
74
Operator in C++ Program



Operators are used to perform operations on variables and values.
An operator is a symbol that operates on a value to perform specific
mathematical or logical computations.
Example:- An operator operates the operands. For example, int c = a + b;
Here, ‘+’ is the addition operator. ‘a’ and ‘b’ are the operands that are being ‘added’.

Operators in C++ can be classified into 6 types:
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Ternary or Conditional Operators
Chapter Six : Programming with C++
75
Operator in C++ Program
1. 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
Chapter Six : Programming with C++
76
Modulo division operator (%): This operator returns remainder after integer division. It is
important to note that during modulo division, the sign of the result is always the sign of first
operand (i.e., numerator). So, if you are interested to get remainder after division operation,
we should use %. For Example:
Chapter Six : Programming with C++
77
Increment and Decrement Operators in C++ Program
 Denoted
as ++ or - Mean increase or decrease by 1
 Pre increment/decrement: ++a, --a
 Increase/decrease
 Post
by 1 before use.
increment/decrement: a++, a—
 Increase/decrease
by 1 after use.
Note: Pre and Post increment/decrement yield different results when
combining with another operation.
For Example:
Chapter Six : Programming with C++
78
Example: Increment and Decrement Operators in C++ Program.
int a = 9, b;

Pre-Increment :


b = a++;
b is 9 and a is 10
Pre-Decrement :


b is 10 and a is 10
Post-Increment:


b = ++a;
b = --a;
b is 8 and a is 8
Post-Decrement:

b = a--;
b is 9 and a is 8
Chapter Six : Programming with C++
79
2. Assignment Operators in C++

Assignment operators are used to assign values to variables.
Chapter Six : Programming with C++
80
For Example:
Copy Operator (Assignment operator)
 Simple copy: a = b;
 Overwrites
the left object (l-value) with the result of the
expression on the right (r-value)
 l-value must be writable

Copy with add
a

+= b; is the same as a = a + b;
Other copy-with-subtract, multiplication, division
behaves the same
a
-= b; a *= b; a /= b; etc
Chapter Six : Programming with C++
81
3. Comparison Operators in C++



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.
Chapter Six : Programming with C++
82
4. Logical Operators in C++
 Logical operators are used to determine the logic between
variables or values.
Operator Name
Description
Example: Let x = 4
&&
Logical
and
Returns true if both
statements are true
x < 5 && x < 10
True
||
Logical
or
Returns true if one of the
statements is true
x < 5 || x < 4
True
!
Logical
not
Reverse the result, returns
false if the result is true
! (x < 5 && x < 10)
False
Return value
Chapter Six : Programming with C++
83
Escape Sequences in C++
 Characters, such as backspace or control characters,
have no visible image and they are nonprintable.
 Other characters ( like single and double quotation
marks, question mark, and backslash) have special
meaning in the language.
 Our programs cannot any of these characters directly.
 Instead, we use an escape sequence (begins with a
backslash (\) to represent such characters.
Chapter Six : Programming with C++
84
The language defines several escape sequences in C++
 \n  New Line
 \t  Horizontal tab
 \b  Backspace
 \”  Double quote
 \’  Single quote
 \\  Backslash
 \?  Question Mark
 \r  Carriage return
 \a  Alert (bell)
85

cin is a predefined variable that reads data from the keyboard with the extraction operator (>>).
Example: Write A C++ program which takes three numbers from the user and returns their sum.
Note:- 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 (>>)
86
Example 2: write the C++ program to find the area of Circle.
Example 3: write the C++ program to find the area of Triangle.
Example 4: write the C++ program to find the area of Rectangle.
Example 5: write the C++ Program For Addition of Two Numbers.
Chapter Six : Programming with C++
87
Conversions for variables Names
 An identifier should give some indication of its meaning.
 Variable names normally are lowercase.



Example:- sum, not Sum or SUM
Classes we define usually begin with an uppercase
letter. Example:- Sales_item
identifiers with multiple words should visually distinguish
each word.

example: student_score or studentScore, not studentScore.
Chapter Six : Programming with C++
88
Scope of a Names
At any particular in a program, each name that is in use refers to a
specific entity like a variable, function, type and so on.
 A given name can be reused to refer to different entities at different
points in the program.
Note: A scope is a part of the program in which a name has a particular
meaning.
{
Most scopes in C++ are delimited by curly braces.
}
 The same name can refer to different entities in different scopes.
 Name are visible from the point where they are declared until the end of
the scope in which the declaration appears.

Chapter Six : Programming with C++
89
Example
#include <iostream>
Using namespace std;
Int main ()
{
Int sum = 0;
for ( int val = 1; val <= 10, ++val )
{
Sum = sum + val;
}
cout << “ sum of 1 to 10 inclusive is”
<< sum << endl;
Return 0;
}
This program defines three names:
main, sum and val
main- defines outside any curly braces.
Has global scope.
It accessible throughout the program.
sum-defined within the scope of block
that is the body of the main function.
Has block scope.
val- defined in the scope of the for
statement.
Chapter Six : Programming with C++
90
The “if” Statement
The if statement is used to
execute a block of code only if a
certain condition is met.
Syntax:
if (condition)
{
// block of code to be executed if the condition is true
}
================================
If statement
Test
False
Conditions
Code inside else block
Optional
True
Code inside if block
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
}
Chapter Six : Programming with C++
91
Chapter Six : Programming with C++
92
The 'while' Statement in C++
A while statement repeatedly executes
a section of code so as a given condition
is true.
Enter while loop
Test
Conditions
FALSE
TRUE
Statements
Exit while loop
Example: 1
#include <iostream>
Using namespace std;
Int main ()
{
Int count = 1;
While (count < = 10)
{
Cout << “Hello there” <<endl;
Count = count + 1;
}
Return 0;
}
Chapter Six : Programming with C++
93
Example: 2
#include <iostream>
Using namespace std;
int main ()
{
int count = 1, sum = 0 ;
While (count < = 10)
{ sum += count + 1;
Count = count + 1;
Cout << “sum of 1 to 10 = ” << sum <<endl;
}
Return 0;
}
Output:-
Chapter Six : Programming with C++
94
Chapter Six : Programming with C++
95
If statement
False
False
If
Condition
Code inside if block
else if
Condition
Code inside else block
True
True
Code inside else if block
The else if statement to specify a new condition if the first condition is false.
Chapter Six : Programming with C++
96
Syntax of
Chapter Six : Programming with C++
97
Example of code
Write a program restaurant that the user is to choice Coffee or Tea to drink.
98

Use the switch statement to select one of many code blocks to be executed.
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.
This is how it works:




The switch expression 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 break and default keywords are optional.
The default keyword specifies some code to run if there is no case match.
99
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.
The break statement can also be used to jump out of a loop.
Chapter Six : Programming with C++
100
3. 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.
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.
 C++ Break:- The break statement can also be used to jump out of a loop.
 The break statement will stop the execution of the innermost loop and start executing
the next line of code after the block.
 C++ Continue: The continue statement breaks one iteration (in the loop),
if a specified condition occurs, and continues with the next iteration in the loop.
Chapter Six : Programming with C++
101
The C++ for loop is used to iterate a part of the program several times.
If the number of iteration is fixed, it is recommended to use for loop than while or
do-while loops.
#include <iostream>
using namespace std;
int main ( )
{
for(int i=1; i<=10; i++)
{
cout << i <<"\n";
}
return 0;
}
Output:
1
2
3
4
5
6
7
8
9
10
Chapter Six : Programming with C++
102
General Syntax For control Statement /Decision Making
Chapter Six : Programming with C++
103
Arrays in C++ program
An array is a collection of variables of the same type that
are referenced by a common name.
 A specific element in an array is accessed by an index.
Single (One) -Dimension Arrays:

The general form of a single-dimension array declaration is:
datatype name[size];
Datatypes declares the base types of the array.
Size defines how many elements the array will hold.
For example: to declare an integer array x of 100 elements, you
would write: int x[100];
Chapter Six : Programming with C++
104
Defining Arrays in C++ program
Using a bracketed list of initializes can initialize array.
For example:

String colors[5] = {“Red”, “Green”, “Yellow”, “Orange”, “White”};
 All arrays have 0 as the index of their first element.
Index of these values are:
Values: Red Green Yellow Orange
White
Index: 0
1
2
3
4
For example:
int A [ 10 ] ; // an array of ten integers.
char string [ 20 ]; //an array of twenty characters.
int a [ 100 ] , b [ 28 ] ; // Defining multiple arrays of same type.
Arrays
105

An array is an ordered list of values
Each value has a numeric index
The entire array
has a single name
0
scores
1
2
3
4
5
6
7
8
9
79 87 94 82 67 98 87 81 74 91
An array of size N is indexed from zero to N-1
This array holds 10 values that are indexed from 0 to 9
Arrays
106
For a one-dimension array, the total size of an array in
bytes is computed as shown here:
total bytes = size of(base type) * number of elements.
For example:
int a[5];
total bytes = 4 * 5 = 20
float b[8];
total bytes = 4 * 8 = 32
double c[3];
total bytes = 8 * 3 = 24
unsigned short int k[7]; total bytes = 2 * 7 = 14
Arrays
107
Things to remember about arrays:
 The
starting index of an array is 0, not 1.
 The size must be an integer constant greater than zero.
 The last index is one less than the size of the array.
 If the array has size elements, the range is 0..size-1.
 Arrays contain data of a single type.
 An array is a sequence of consecutive elements in memory
and the start of the array is the address of its first element.
Arrays
108
Rules of arrays:
 If
the array size is given in brackets, then the initialized list
must have at most that many values in it.
 If it has fewer, the rest of the array is initialized to 0's.
 If the size is not given in brackets, then the size is equal to
the number of elements in the initializer list.
 If there is no initializer list, none of the array elements are
initialized.
Advice
Always named constants for the sizes of arrays. It makes it
easier to write, maintain, and read the code.
Chapter Six : Programming with C++
109
Syntax of array:
datatype name[n];
Here,
datatype: type of element to be stored.
name: name of the array.
n: the size of the array.
For example:String colors[5];
String colors[5] = {“Red”, “Green”, “Yellow”, “Orange”, “White”};
Arrays in C++ Program
110
Instead of displaying all elements one by one.

We can automate them using loops.
For Example using for loop to display all elements of an array.
#include <iostream>
using namespace std;
int main ( ) {
String students[4] = {“Kayo”, “Falmi”, “Nimona”, “Barano”};
for (int index = o; index < 4; index++) {
Output
cout << students[index] <<endl;
Kayo
}
Falmi
Nimona
Return o;
Barano
}
Arrays in C++ Program
111
Multidimensional Arrays
it is an array of arrays.
Syntax:
datatype name [n][m];
Here,

datatype : type of element to be stored.
 name : name of the array.
 n : the size of the row array.
 m : the size of the column array.
For Example:
String Students[2][5] = {
{ “Elsa”, “Esset”, “Naol”, “Kanalamin”, “Oromia” },

{ “Bona”, “Erga”, “Deborah”, “Abdi”, “Fenanim” }
};
Return 0;
}
Arrays in C++ Program
112
The data in multidimensional array is stored in a tabular form as
shown in the diagram below:
int arr[2][3]={{10, 11 ,12} , {20 ,21 , 22}};
Accessing array elements:
C++ Functions
113
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 a function, specify the name of the function, followed by
parentheses ( ):
C++ Functions
114
To Create a Function
Syntax:
Example Explained
 myFunction() is the name of the function
 void means that the function does not have a return value.
 inside the function (the body), add code that defines what
the function should do.
Call a Function
 To call a function, write the function's name followed by two
parentheses () and a semicolon ;
Note Syntax: functionName( );
C++ Functions
115
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 a function, specify the name of the function, followed by
parentheses ( ):
C++ Functions
116
The function in C++ language is also known as procedure or
subroutine in other programming languages.
 A function is a group of statements that together perform a task.
 Every C++ program has at least one function, which is main(), and
all the most trivial programs can define additional functions.
 A function declaration tells the compiler about a function's name,
return type, and parameters.
 A function definition provides the actual body of the function.
Declaration of a function


The syntax of creating function in C++ language is given below:
return_type function_name(data_type, parameter...)
{
//code to be executed
}
C++ Functions
117
A C++ function definition consists of a function header and a function body.
Here are all the parts of a function: Return Type − A function may return a value.


The return_type is the data type of the value the function returns.
Some functions perform the desired operations without returning a value.


Function Name − This is the actual name of the function.


The function name and the parameter list together constitute the function
signature.
Parameters − A parameter is like a placeholder.
When a function is invoked, you pass a value to the parameter.
 This value is referred to as actual parameter or argument.
 The parameter list refers to the type, order, and number of the parameters of a
function.
 Parameters are optional; that is, a function may contain no parameters.
Function Body − The function body contains a collection of statements that define
what the function does.


In this case, the return_type is the keyword void.
Function Overloading
118
If multiple functions having same name but parameters of the
functions should be different is known as Function Overloading.
 When a function name is overloaded with different jobs it is
called Function Overloading.
 In Function Overloading “Function” name should be the same and
the arguments should be different.

Example of Function Overloading
119
Consider the following example, which have two functions that add
numbers of different type:
The main advantage of function overloading is to the improve the code readability and
allows code reusability.
Pointers in C++ Program
120




A pointer is a special variable that is used to store the address of some
other variable.
A pointer can be used to store the address of a single variable, array,
structure or even a pointer.
A pointer is a derived datatype.
To declare a pointer, we use the asterisk (*) symbol before the variable
name.
Note: A pointer however, is a variable that stores the memory address as its value.
Syntax: datatype *name;
For Example:



int *ptr1; //pointer to integer type.
float *ptr2; //pointer to float type.
char *ptr3; //pointer to character type.
Pointers in C++ Program
121
Reference or Address-of operator (&)

As the name suggests, it gives the address of a variable.

b=&c; // The address of ‘c’ is stored in ‘b’.
Referencing means making a pointer point to a variable.
 Address of operator (“&”) is known as referencing operator.
 This operator returns the address of the variable associated with
the operator.
For Example:

if we write “&x”, it will return the address of the variable ‘x’.
 Hence, if we have a pointer “p”, which we want to point to a variable x,
then we need to copy the address of the variable “x” in the pointer
variable “p”.
 This is implemented by the statement: p = &x;

Pointers in C++ Program
122
Dereference or Value of operator (*)

Dereference operator operates on a pointer value and returns
the location value.

b = *c; // it returns the value at ‘b’ (memory location of ‘c’).
 i.e b = *(&c) or the value at the memory location of ‘c’. w/c is
nothing but the value of c.
Value of operator (“*”) is known as dereference operator.
 This operator returns the value stored in the variable pointed by
the specified pointer.
For Example:
 if we write “*p”, it will return the value of the variable pointed
by the pointer “p”.
 Hence, if we want the value of the variable pointed by the
pointer “p” to be stored in a variable “y”, then the expression
can be written as: y = *p;

Some Application of Pointers in C++ program
123
What is call by value and call by reference in C++ Program?

In call by value method, we pass the copies of actual
parameters to the function’s formal parameters.
 This
means if there is any change in the values inside the
function, then, that change will not affect the actual values.

In call by reference method, the reference or address
of actual parameters is sent to the function’s formal
parameters.
 This
means any change in values inside the function will be
reflected in the actual values.
Chapter Six : Programming with C++
124
Galatoomaa!
Technology is passport for future life!
Thank You!
Download