0% found this document useful (0 votes)
17 views209 pages

Programming and Problem Solving

The document outlines a course on Programming and Problem-Solving at Ghana Communication Technology University, covering key concepts such as programming, problem-solving, algorithms, and pseudocode. It explains the process of programming, the benefits of learning it, and provides examples of algorithms and flowcharts. Additionally, it details control structures, properties of algorithms, and various types of conditional statements.

Uploaded by

odonkorraphael9
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
0% found this document useful (0 votes)
17 views209 pages

Programming and Problem Solving

The document outlines a course on Programming and Problem-Solving at Ghana Communication Technology University, covering key concepts such as programming, problem-solving, algorithms, and pseudocode. It explains the process of programming, the benefits of learning it, and provides examples of algorithms and flowcharts. Additionally, it details control structures, properties of algorithms, and various types of conditional statements.

Uploaded by

odonkorraphael9
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

GHANA COMMUNICATION TECHNOLOGY UNIVERSITY

DEPARTMENT OF COMPUTER SCIENCE

CSSD 101: Programming and Problem-Solving

By:

Gideon Owusu Agyeman


Tel: +233200340000
Email: gideongenius@[Link] / me@[Link]
Website: [Link]

Programming and Problem solving 1


Outline
• Programming
• Problem Solving
• Algorithm
• Examples of Algorithm
• Properties of an Algorithm

Programming and Problem solving 2


Programming
• Programming, also sometimes called coding
• The process of giving a computer a set of instructions to
follow.
• It's like writing a recipe for the computer, where each step
tells it what to do and how to do it.
• These instructions are written in a specific language that the
computer can understand, known as a programming
language.

Programming and Problem solving 3


How it works:
[Link] code: You write code in a programming
language, like Python, Java, or C++. This code is made up of
lines of text that contain instructions and commands.
[Link] code: The code is then translated into a
language the computer understands, often with the help of a
compiler or interpreter.
[Link] code: Once the computer understands the
code, it can execute it, meaning it carries out the instructions
you programmed.
Programming and Problem solving 4
What it does:
• Instructs computers: Programming allows you to control
computers and make them perform specific tasks.
• Solves problems: It's a powerful tool for solving problems
and automating processes in various fields, from websites
and apps to scientific simulations and video games.
• Creates programs: The end result of programming is called a
program, which is a set of code that can be executed by a
computer.

Programming and Problem solving 5


What are the benefits
of learning
programming?
Programming and Problem solving 6
Benefits of learning programming:
• Boosts problem-solving skills: Programming teaches you to
think logically and break down problems into smaller, more
manageable steps.
• Enhances creativity: It allows you to express your ideas and
bring them to life through code.
• Opens career opportunities: Programming skills are in high
demand across various industries, and can lead to exciting
and rewarding careers.

Programming and Problem solving 7


Problem Solving
• Can you think of a day in your life that goes without
problem-solving? The answer to this question is of course,
No.
• All these activities involve some kind of problem-solving.
• It can be said that whatever activity a human being or
machine does to achieve a specified objective comes under
problem-solving.

Programming and Problem solving 8


Examples of Problem solving
• Preparing food to eat is a problem solving
•?
•?
•?

Programming and Problem solving 9


Problem solving
• Problem is a kind of barrier to achieve something and
problem solving is a process to get that barrier removed by
performing some sequence of activities.
• Note that all the problems in the world can not be solved.
• There are some problems which have no solution and these
problems are called Open Problems.
• If you can solve a given problem then you can also write an
algorithm for it.

Programming and Problem solving 10


Algorithm
• A step by step approaching for solving a particular problem.
• Algorithm can be defined as: “A sequence of activities to be
processed for getting desired output from a given input.”

• Before writing an algorithm for a problem, one should find


out what is/are the inputs to the algorithm and what is/are
expected output after running the algorithm.

Programming and Problem solving 11


Algorithm
• While writing algorithms we will use following symbol for
different operations:
• ‘+’ for Addition
• ‘-’ for Subtraction
• ‘*’ for Multiplication
• ‘/’ for Division and
• ‘ ’ for assignment.
• ‘= ’ for assignment.
• For example A  X*3 or A = X*3 means A will have a value of X*3
Programming and Problem solving 12
Example of algorithm
• How to prepare palm nut soup?
• How to prepare Banku?

Programming and Problem solving 13


Example of algorithm
• Problem 1: Find the area of a Circle of radius r.

• Inputs to the algorithm: Radius r of the Circle.


• Expected output: Area of the Circle Algorithm:

• Step1: Read\input the Radius r of the Circle


• Step2: Area = PI*r*r // calculation of area
• Step3: Print Area
Programming and Problem solving 14
Example of algorithm
• Problem2: Write an algorithm to read two numbers and find
their sum.

• Inputs to the algorithm:


• First num1.
• Second num2.
• Expected output:
• Sum of the two numbers.

Programming and Problem solving 15


Example of algorithm

• Step1: Start
• Step2: Read\input the first num1.
• Step3: Read\input the second num2.
• Step4: Sum <- num1+num2 // calculation of sum
• Step5: Print Sum
• Step6: End

Programming and Problem solving 16


Algorithm
• Three types of control structures.
• 1. Sequence
• 2. Branching (Selection)
• 3. Loop (Repetition)

• These three control structures are sufficient for all purposes.


The sequence is exemplified by sequence of statements
place one after the other – the one above or before another
gets executed first.
Programming and Problem solving 17
Example of algorithm(Branch)
• Problem1: write algorithm to find the greater number
between two numbers

• Step1: Start
• Step2: Read/input A and B
• Step3: If A greater than B then C=A
• Step4: if B greater than A then C=B
• Step5: Print C
• Step6: End
Programming and Problem solving 18
Example of algorithm(Branch)
• Problem2: write algorithm to find the result of equation:

• Step1: Start
• Step2: Read/input x
• Step3: If X Less than zero then F=-X
• Step4: if X greater than or equal zero then F=X
• Step5: Print F
• Step6: End
Programming and Problem solving 19
Example of algorithm(Branch)
• Problem3: A algorithm to find the largest value of any three
numbers.
• Step1: Start
• Step2: Read/input A,B and C
• Step3: If (A>=B) and (A>=C) then Max=A
• Step4: If (B>=A) and (B>=C) then Max=B
• Step5:If (C>=A) and (C>=B) then Max=C
• Step6: Print Max
• Step7: End
Programming and Problem solving 20
Example of algorithm(Loop)
• Problem 1: An algorithm to print even numbers between 0
and 99

• 1. Start
• 2. I ← 0
• 3. Write I in standard output // Print I
• 4. I ← I+2
• 5. If (I <=98) then go to line 3
• 6. End
Programming and Problem solving 21
Example of algorithm(Loop)
• Problem 2: An algorithm to print odd numbers between 0
and 99

• 1. Start
• 2. I ← 1
• 3. Write I in standard output // Print I
• 4. I ← I+2
• 5. If (I <=98) then go to line 3
• 6. End
Programming and Problem solving 22
Example of algorithm(Loop)
• Problem 2: Design an algorithm that gets a natural value ‘n’
as its input and calculates odd numbers equal to or less than
‘n’.
• 1. Start
• 2. Read n
• 3. I ← 1
• 4. Write I
• 5. I ← I + 2
• 6. If ( I <= n) then go to line 4
• 7. End Programming and Problem solving 23
Algorithm

• Think about a problem


• Lets write an algorithm for the problem

Programming and Problem solving 24


Properties of Algorithm
Donald Ervin Knuth has given a list of five properties for
algorithm, these properties are:
• 1) Finiteness: An algorithm must always terminate after a
finite number of steps.
• 2) Definiteness: Each step of an algorithm must be
precisely defined.
• 3) Input:
• 4) Output:
• 5) Effectiveness:

Programming and Problem solving 25


PSEUDOCODE AND FLOWCHART
• Lecture 2

Programming and Problem solving 26


GHANA COMMUNICATION TECHNOLOGY UNIVERSITY
DEPARTMENT OF COMPUTER SCIENCE

CSSD 101: Programming and Problem-Solving (Lecture 2)

By:

Gideon Owusu Agyeman


Tel: +233200340000 / +233546441122
Email: gideongenius@[Link] / me@[Link]
Website: [Link]

Programming and Problem solving 1


Algorithm and Flowchart
• Pseudocode
• Conditional algorithms
• If statement
• If else statement
• If elseif else statement
• Nested if statement
• Flowchart
• Symbols
• Examples of flowchart

Programming and Problem-Solving 2


Pseudocode
• Pseudocode is a high-level description of an algorithm or a program
written in plain English or any other natural language. It is not tied to
the syntax of a specific programming language, allowing developers
and programmers to express the logic and structure of an algorithm
without getting into the details of programming language syntax.
• The purpose of pseudocode is to provide a clear and understandable
representation of the algorithm's steps, making it easier for
individuals to design, communicate, and understand algorithms
before translating them into actual code. Pseudocode is often used
during the early stages of software development for planning and
discussion.

Programming and Problem-Solving 3


Key characteristics of pseudocode include:
[Link]: Pseudocode is not a strict formalism. It allows for
flexibility in expressing ideas without adhering to the rigid syntax of a
programming language.
[Link]: Pseudocode is designed to be easily readable and
understandable by people who may not be familiar with a specific
programming language.
[Link]: It focuses on the logical flow of an algorithm without
getting into low-level implementation details.
[Link] Standardization: There is no standardized syntax for pseudocode.
Different individuals may use slightly different conventions, but the
emphasis is on clarity and simplicity.
Programming and Problem-Solving 4
Pseudocode example 1:
[Link] to compare two numbers

1. Enter or get number 1 and number 2


2. If number 1 is greater than number 2 then
Number 1 is greater
3. Else since number 1 is not greater than number 2
Number 2 is greater

Programming and Problem-Solving 5


Pseudocode example 2:
[Link] to check if you can vote in 2024 election

1. Enter or get age


2. If age is greater or equal to 18 then
You qualify to vote
3. Else since age is less than 18
You don’t qualify to vote

Programming and Problem-Solving 6


If statement
• Find the greatest number among two given numbers

• Start
• Input a
• Input b
• If a > b
• Print a is greater
• End

Programming and Problem-Solving 7


If statement
• An algorithm to check if you are 18 years to vote in 2024 election

• Start
• Input age
• If age>=18
• Print “You qualify to vote in 2024 election”
• End

Programming and Problem-Solving 8


If else statement
• Find the greatest number among two given numbers
• Start
• Input a
• Input b
• If a > b
• Print a is greater
• Else
• Print b is greater
• End

Programming and Problem-Solving 9


If else statement
• An algorithm to check if you are 18 years to vote in 2024 election

• Start
• Input age
• If age>=18
• Print “You qualify to vote in 2024 election”
• Else
• Print “You do not qualify to vote in Ghana”
• End
Programming and Problem-Solving 10
If elseif statement
• An algorithm to check if you are 18 years to vote in 2024 election

• Start
• Input age
• If age>=18
• Print “You qualify to vote in 2024 election”
• elseIf HasVotedBefore
• Print “You can vote with your previous voter ID card in 2024”
• Else
• “You do not qualify to vote in 2024 election”
• End Programming and Problem-Solving 11
An algorithm to check if you are 18 years and
has voter ID card to vote in 2024 election

• Input age
• Input VoterCard
• If age>=18
• If hasVoterCard //Boolean expression
• Print “You can vote in 2024”
• Else
• Print “You need to apply for the voter card before you can vote”

• Else
• Print “You are not eligible to vote”

Programming and Problem-Solving 12


Nested If statement
Find the greatest number among three given numbers and find
if the biggest number is even or odd

• Input a, b, c • Else
• IF c MOD 2 == 0
• If a > b and a > c • Print c is greater and even
• IF a MOD 2 == 0 • Else
• Print a is greater and even • Print c is greater and odd
• Else
• Print a is greater and odd
• Else if b>a and b>c
• IF b MOD 2 == 0
• Print b is greater and even
• Else
• Print b is greater and odd

Programming and Problem-Solving 13


Flowchart
• The flowchart is a diagram that visually/diagrammatically presents
the flow of data through processing systems.
• This means by seeing a flow chart one can know the operations
performed and the sequence of these operations in a system.
• Algorithms are nothing but a sequence of steps for solving problems.
So a flow chart can be used for representing an algorithm.
• A flowchart, will describe the operations (and in what sequence) are
required to solve a given problem. You can see a flow chart as a
blueprint of a design you have made for solving a problem.

Programming and Problem-Solving 14


Flowchart
• There are 6 basic symbols commonly used in the
flowcharting of assembly language Programs:
• Terminal, Process, input/output, Decision, Connector and
Predefined Process.
• This is not a complete list of all the possible flowcharting
symbols, it is the ones used most often in the structure of
Assembly language programming.

Programming and Problem-Solving 15


Some Basic Flowchart Symbols
[Link]/End/Terminal Symbol: 5. Flow Arrow:
1. Description: Represents the beginning or end 1. Description: Indicates the direction of flow
of a process. from one step to another.
2. Shape: Oval 2. Shape: Arrow connecting two symbols
[Link] Symbol: 6. Connector Symbol:
1. Description: Represents a process or activity. 1. Description: Represents a connection point
2. Shape: Rectangle between different parts of the flowchart. Often
used to avoid crossing lines.
[Link] Symbol: 2. Shape: Small circle
1. Description: Indicates a decision point where a
question is asked, and the flowchart branches 7. Predefined Process Symbol:
based on the answer. 1. Description: Represents a process or activity that
2. Shape: Diamond is defined elsewhere in the flowchart or in
another document.
[Link]/Output Symbol: 2. Shape: Rectangle with double vertical bars on the
1. Description: Represents input or output of sides
data.
2. Shape: Parallelogram
Programming and Problem-Solving 16
Some Basic Flowchart Symbols

Programming and Problem-Solving 17


General Rules for flowcharting
• All boxes of the flowchart are connected with Arrows. (Not lines)
• Flowchart symbols have an entry point on the top of the symbol
with no other entry points. The exit point for all flowchart symbols
is on the bottom except for the Decision symbol.
• The Decision symbol has two exit points; these can be on the sides
or the bottom and one side (Yes/No, True/False).
• Generally a flowchart will flow from top to bottom. However, an
upward flow can be shown as long as it does not exceed 3 symbol

Programming and Problem-Solving 18


General Rules for flowcharting
• Connectors are used to connect breaks in the flowchart.
• Examples are: • From one page to another page. • From
the bottom of the page to the top of the same page.
• All flow charts start with a Terminal or Predefined Process
(for interrupt programs or subroutines) symbol.
• All flowcharts end with a terminal.

Programming and Problem-Solving 19


General Rules for flowcharting
• Flowcharting uses symbols that have been in use for several
years to represent the type of operations and/or processes
being performed.
• The standardized format provides a common method for
people to visualize problems together in the same manner.
• The use of standardized symbols makes the flow charts
easier to interpret, however, standardizing symbols is not as
important as the sequence of activities that make up the
process.
Programming and Problem-Solving 20
Example of flowchart

Start

END
Programming and Problem-Solving 21
Example of flowchart
• Problem 2: Flowchart for an algorithm which gets two numbers and
prints sum of their value
Start

End

Programming and Problem-Solving 22


Example of flowchart
• Problem 3: Algorithm for finding the greater number between two
numbers.

Programming and Problem-Solving 23


Example of flowchart
• Problem 4:
Flowchart to calculate
the average from 25 exam scores.

Programming and Problem-Solving 24


Assignment 1
• Watch the following YouTube video and set
up C++ on your computer before our next
meeting
• [Link] • Copy the following codes put
them in your editor and replace
D7wfhgNY your full name with Gideon.
• Download the software from the link below
• [Link] #include <iostream>
using namespace std;

• Take a screenshot of your editor printing int main() {


your name and submit it to my email. cout << "Hello World!";
cout << “ My name is Gideon ";
return 0;
• Submission date: 16th February 2024 }
• Email: gideongenius2@[Link]
Programming and Problem-Solving 25
Assignment 2
• Get any societal problem of your choice
• i. Write an algorithm for the problem
• Ii. Draw a flowchart for the problem making sure the decision symbol
is used in the flowchart.

• Submission date: 20th February 2024


• Email: gideongenius2@[Link]

Programming and Problem-Solving 26


GHANA COMMUNICATION TECHNOLOGY UNIVERSITY
DEPARTMENT OF COMPUTER SCIENCE

CSSD 101: Programming and Problem-Solving (Lecture 2)

By:

Gideon Owusu Agyeman


Tel: +233200340000 / +233546441122
Email: gideongenius@[Link] / me@[Link]
Website: [Link]

Programming and Problem solving 1


C++ Program
• Before starting the abcd of C++ language, you need to learn how to write,
compile and run the first C++ program.
• To write the first C++ program, open the C++ console and write the following
code:

1. #include <iostream>
2. using namespace std;
3.
4. int main() {
5. cout << "Hello World!";
6. Return 0;
}

Programming and Problem-Solving 2


C++ Program
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: A blank line. C++ ignores white space. But we use it to


make the code more readable.
Line 4: Another thing that always appear in a C++ program is int
main(). This is called a function. Any code inside its curly
brackets {} will be executed.
Line 5: cout (pronounced "see-out") is an object used together with
the insertion operator (<<) to output/print text. In our example, it
will output "Hello World!".

Programming and Problem-Solving 3


C++ Program
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; }

Remember: The compiler ignores white spaces. However,


multiple lines makes the code more readable.
Line 6: return 0 ends the main function.
Line 7: Do not forget to add the closing curly bracket }
to actually end the main function.

Programming and Problem-Solving 4


Omitting Namespace
You might see some C++ programs that runs without the
standard namespace library.
The using namespace std line can be omitted and replaced with
the std keyword, followed by the :: operator for some objects:

Example
#include <iostream>

int main(){
std::cout<<"Hello World!";
return 0;
}
Programming and Problem-Solving 5
C++ Variables
• Variables are the fundamental building blocks of data manipulation and storage in
programming, acting as dynamic containers for data in the C++ programming language.
A variable is more than just a memory label. It serves as a link between abstract ideas
and concrete data storage, allowing programmers to deftly manipulate data.
• With the help of C++ variables, developers may complete a wide range of jobs, from
simple arithmetic operations to complex algorithmic designs. These programmable
containers can take on a variety of shapes, such as integers, floating-point numbers,
characters, and user-defined structures, each of which has a distinctive impact on the
operation of the program.
• Programmers follow a set of guidelines when generating variables, creating names that
combine alphanumeric letters and underscores while avoiding reserved keywords. More
than just placeholders, variables are what drive user input, intermediary calculations,
and the dynamic interactions that shape the program environment.
• A variable is a name of memory location. It is used to store data. Its value can be
changed and it can be reused many times.

Programming and Problem-Solving 6


C++ Variables - Rules for defining variables
• A variable can have alphabets, digits and underscore.
• A variable name can start with alphabet and underscore only. It can't
start with digit.
• No white space is allowed within variable name.
• A variable name must not be any reserved word or keyword e.g. char,
float etc.

• Rules and Naming: Variable names must begin with a letter or an underscore, avoid
reserved keywords, and be composed of letters, numbers, and underscores.

Programming and Problem-Solving 7


C++ Variables - syntax to declare a variable:
• Variable declaration: Use the syntax type variable_name to define a
variable, containing its type and name.
• Initialization: When a variable is declared, it can be given a value,
such as int age = 25.

Programming and Problem-Solving 8


C++ Variables - syntax to declare a variable:
• type variable_list;
• The example of declaring variable is given below:
[Link] x;
[Link] y;
[Link] z;

Here, x, y, z are variables and int, float, char are data types.

Programming and Problem-Solving 9


C++ Variables - syntax to declare a variable:
• We can also provide values while declaring the variables as given
below:
[Link] x=5,b=10; //declaring 2 variable of integer type
[Link] f=30.8;
[Link] c='A';

Programming and Problem-Solving 10


C++ Variables - Rules for defining variables
• Valid variable names:
[Link] a;
[Link] _ab;
[Link] a30;

• Invalid variable names:


[Link] 4;
[Link] x y;
[Link] double;

Programming and Problem-Solving 11


Uses of C++ Variables:
• There are several uses of variables in C++. Some main uses of C++ variables
are as follows:
• Important Ideas: Programming is fundamentally based on C++ variables,
which allow for the storing, manipulation, and interaction of data inside a
program.

• Memory Storage: Variables are named memory regions that may hold values
of different data kinds, ranging from characters and integers to more intricate
user-defined structures.
• Dynamic character: Programming that is responsive and dynamic is made
possible by the ability to assign, modify, and reuse data through variables.
• Data Types: The several data types that C++ provides, including int, float,
char, and others, each define the sort of value that a variable may store.

Programming and Problem-Solving 12


Data Types
• A data type specifies the type of data that a variable can store such as
integer, floating, character etc.

Programming and Problem-Solving 13


Data Types
• A data type specifies the type of data that a variable can store such as
integer, floating, character etc.

Programming and Problem-Solving 14


Data Types
Basic Data Types
The basic data types are integer-based and floating-point based. C++
language supports both signed and unsigned literals.

The memory size of basic data types may change according to


32 or 64 bit operating system.

Programming and Problem-Solving 15


Data Types

Programming and Problem-Solving 16


Data Types

Programming and Problem-Solving 17


Data Types

Programming and Problem-Solving 18


Data Types

Programming and Problem-Solving 19


C++ Basic Input/Output
• C++ I/O operation is using the stream concept. Stream is the
sequence of bytes or flow of data. It makes the performance fast.
• If bytes flow from main memory to device like printer, display screen,
or a network connection, etc, this is called as output operation.
• If bytes flow from device like printer, display screen, or a network
connection, etc to main memory, this is called as input operation.

Programming and Problem-Solving 20


C++ Basic Input/Output

Programming and Problem-Solving 21


C++ Basic Input/Output

Programming and Problem-Solving 22


C++ Basic Input/Output

Programming and Problem-Solving 23


C++ Basic Input/Output

Programming and Problem-Solving 24


Keywords
• C++ keywords play a crucial role in defining the syntax and
functioning of the language. They include reserved words with
functions, such as specifying data types, managing program flow,
and activating additional features. Understanding these terms is
essential for good C++ programming and enables programmers to
build reliable and adaptable software.
• A keyword is a reserved word. You cannot use it as a variable name,
constant name etc. A list of 32 Keywords in C++ Language which are
also available in C language are given below.

Programming and Problem-Solving 25


Kewords

Programming and Problem-Solving 26


Keywords
• auto: In C++, the auto keyword is mainly used for type inference. It enables the
compiler to determine a variable's data type from its initializer expression.
• break: By using the break keyword, the execution of a loop or switch
statement is stopped.
• case: It is used in a switch statement to provide several scenarios in which
different code blocks should be run depending on the result of an expression.
• char: The char keyword is used to declare character variables or data types.
• const: Constant values or pointers that refer to constants are declared with the
keyword const.
• Continue: This keyword is used to go on to the next iteration of a loop without
running the last remaining statements.

Programming and Problem-Solving 27


Keywords
• default: When no other case matches, it is used in a switch statement to
provide a default case.
• Do: This keyword initiates a loop that runs a series of statements as long as a
certain condition is met.
• double: Double-precision floating-point variables and data types are declared
with the double keyword.
• else: It works in conjunction with the if statement to specify an alternative
code snippet that is run if the condition is false.
• float: The float keyword is used to declare single-precision floating-
point variables or data types.
• If: This operator is used to run a block of code only if a certain condition is
met.
• int: The int keyword is used to declare the integer variables or data types.
Programming and Problem-Solving 28
C++ Operators
• An operator is simply a symbol that is used to perform operations. There can be
many types of operations like arithmetic, logical, bitwise etc.
• There are following types of operators to perform different types of operations in
C language.
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operator
• Unary operator
• Ternary or Conditional Operator
• Misc Operator
Programming and Problem-Solving 29
C++ Operators

Programming and Problem-Solving 30


C++ Expression
• C++ expression consists of operators, constants, and variables which
are arranged according to the rules of the language.
• It can also contain function calls which return values.
• An expression can consist of one or more operands, zero or more
operators to compute a value.
• Every expression produces some value which is assigned to the
variable with the help of an assignment operator.

Programming and Problem-Solving 31


C++ Expression
[Link]

2.(a+b) - c
3.(x/y) -z
4.4a2 - 5b +c
5.(a+b) * (x+y)

Programming and Problem-Solving 32


C++ Expression
[Link]

2.(a+b) - c
3.(x/y) -z
4.4a2 - 5b +c
5.(a+b) * (x+y)

Programming and Problem-Solving 33


C++ Expression

Programming and Problem-Solving 34


•Control Statement

Programming and Problem-Solving 35


If Statement
1.#include <iostream>
[Link] namespace std;
3.
4. int main () {
5. int num = 10;
6. if (num % 2 == 0)
7. {
8. cout<<"It is even number";
9. }
10. return 0;
11.}

Programming and Problem-Solving 36


C++ While loop
[Link](condition){
2.//code to be executed
3.}

Programming and Problem-Solving 37


1.#include <iostream>
[Link] namespace std;
[Link] main() {
4. int i=1;
5. while(i<=10)
6. {
7. cout<<i <<"\n";
8. i++;
9. }
10. }

Programming and Problem-Solving 38


C++ Do-While Loop
[Link]{
2.//code to be executed
3.}while(condition);

Programming and Problem-Solving 39


1.#include <iostream>
[Link] namespace std;
[Link] main() {
4. int i = 1;
5. do{
6. cout<<i<<"\n";
7. i++;
8. } while (i <= 10) ;
9.}

Programming and Problem-Solving 40


C++ For Loop
[Link](initialization; condition; incr/decr){
2.//code to be executed
3.}

Programming and Problem-Solving 41


1.#include <iostream>
[Link] namespace std;
[Link] main() {
4. for(int i=1;i<=10;i++){
5. cout<<i <<"\n";
6. }
7. }

Programming and Problem-Solving 42


C++ switch
1. switch(expression){
2. case value1:
3. //code to be executed;
4. break;
5. case value2:
6. //code to be executed;
7. break;
8. ......
9.
[Link]:
11. //code to be executed if all cases are not matched;
12. break;
13.}

Programming and Problem-Solving 43


1. #include <iostream>
2. using namespace std;
3. int main () {
4. int num;
5. cout<<"Enter a number to check grade:";
6. cin>>num;
7. switch (num)
8. {
9. case 90: cout<<"It is 90"; break;
10. case 80: cout<<"It is 80"; break;
11. case 70: cout<<"It is 70"; break;
12. default: cout<<"Not 90, 80 or 70"; break;
13. }
14. }

Programming and Problem-Solving 44


C++ Break Statement
• The C++ break is used to break loop or switch statement. It breaks the
current flow of the program at the given condition. In case of inner
loop, it breaks only inner loop.

[Link]-statement;
[Link];

Programming and Problem-Solving 45


[Link] main() {
2. for (int i = 1; i <= 10; i++)
3. {
4. if (i == 5)
5. {
6. break;
7. }
8. cout<<i<<"\n";
9. }
10.}

Programming and Problem-Solving 46


C++ Continue Statement
• The C++ continue statement is used to continue loop. It continues the
current flow of the program and skips the remaining code at specified
condition. In case of inner loop, it continues only inner loop.

[Link]-statement;
[Link];

Programming and Problem-Solving 47


C++ Goto Statement
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. ineligible:
6. cout<<"You are not eligible to vote!\n";
7. cout<<"Enter your age:\n";
8. int age;
9. cin>>age;
10. if (age < 18){
11. goto ineligible;
12. }
13. else
14. {
15. cout<<"You are eligible to vote!";
16. }
17.}

Programming and Problem-Solving 48


GHANA COMMUNICATION TECHNOLOGY UNIVERSITY
DEPARTMENT OF COMPUTER SCIENCE

CSSD 101: Programming and Problem-Solving (Lecture 5)

By:

Gideon Owusu Agyeman


Tel: +233200340000 / +233546441122
Email: gideongenius@[Link] / me@[Link]
Website: [Link]

Programming and Problem solving 1


•Control Statement

Programming and Problem-Solving 2


If Statement
1.#include <iostream>
[Link] namespace std;
3.
4. int main () {
5. int num = 10;
6. if (num % 2 == 0)
7. {
8. cout<<"It is even number";
9. }
10. return 0;
11.}

Programming and Problem-Solving 3


C++ While loop
[Link](condition){
2.//code to be executed
3.}

Programming and Problem-Solving 4


1.#include <iostream>
[Link] namespace std;
[Link] main() {
4. int i=1;
5. while(i<=10)
6. {
7. cout<<i <<"\n"; // cout<<i <<endl;
8. i++;
9. }
10. }

Programming and Problem-Solving 5


C++ Do-While Loop
[Link]{
2.//code to be executed
3.}while(condition);

Programming and Problem-Solving 6


1.#include <iostream>
[Link] namespace std;
[Link] main() {
4. int i = 1;
5. do{
6. cout<<i<<"\n";
7. i++;
8. } while (i <= 10) ;
9.}

Programming and Problem-Solving 7


C++ For Loop
[Link](initialization; condition; incr/decr){
2.//code to be executed
3.}

Programming and Problem-Solving 8


1.#include <iostream>
[Link] namespace std;
[Link] main() {
4. for(int i=1;i<=10;i++){
5. cout<<i <<"\n";
6. }
7. }

Programming and Problem-Solving 9


C++ switch
1. switch(expression){
2. case value1:
3. //code to be executed;
4. break;
5. case value2:
6. //code to be executed;
7. break;
8. ......
9.
[Link]:
11. //code to be executed if all cases are not matched;
12. break;
13.}

Programming and Problem-Solving 10


1.#include <iostream>
[Link] namespace std;
[Link] main () {
4. int num;
5. cout<<"Enter a number to check grade:";
6. cin>>num;
7. switch (num)
8. {
9. case 90: cout<<"It is 90"; break;
10. case 80: cout<<"It is 80"; break;
11. case 70: cout<<"It is 70"; break;
12. default: cout<<"Not 90, 80 or 70"; break;
13. }
14. }

Programming and Problem-Solving 11


C++ Break Statement
• The C++ break is used to break loop or switch statement. It breaks the
current flow of the program at the given condition. In case of inner
loop, it breaks only inner loop.

[Link]-statement;
[Link];

Programming and Problem-Solving 12


C++ Break Statement
• #include <iostream> • Output
• using namespace std; • The number is 1
• int main (){ • The number is 2
• for(int i=1; i<=10; i++){ • The number is 3
• if(i==5){ • The number is 4
• break;
• }
• cout<<"The number is "<<i<<"\n";
• }
• }

Programming and Problem-Solving 13


C++ Continue Statement
• The C++ continue statement is used to continue loop. It continues the
current flow of the program and skips the remaining code at specified
condition. In case of inner loop, it continues only inner loop.

[Link]-statement;
[Link];

Programming and Problem-Solving 14


C++ Continue Statement
• #include <iostream> • Output
• using namespace std; • The number is 1
• int main (){ • The number is 2
• for(int i=1; i<=10; i++){ • The number is 3
• if(i==5){ • The number is 4
• continue; • The number is 6
• } • The number is 7
• cout<<"The number is "<<i<<"\n"; • The number is 8
• } • The number is 9
• The number is 10
•}

Programming and Problem-Solving 15


C++ Goto Statement
1. #include <iostream>
2. using namespace std;
3. int main()
• Output
4. {
• You are not eligible to vote!
5. ineligible:
• Enter your age:
6. cout<<"You are not eligible to vote!\n";
• 15
7. cout<<"Enter your age:\n";
• You are not eligible to vote!
8. int age;
• Enter your age:
9. cin>>age;
• 17
10. if (age < 18){ • You are not eligible to vote!
11. goto ineligible;
• Enter your age:
12. }
• 19
13. else
• You are eligible to vote!";
14. {
15. cout<<"You are eligible to vote!";
16. }
Programming and Problem-Solving 16
17.}
C++ Functions

Programming and Problem-Solving 17


C++ Functions
• The function in C++ language is also known as procedure or
subroutine in other programming languages.
• To perform any task, we can create function. A function can
be called many times. It provides modularity and code
reusability.

Programming and Problem-Solving 18


Advantage of functions in C++
• Code Reusability
• By creating functions in C++, you can call it many times. So
we don't need to write the same code again and again.
• Code optimization
• It makes the code optimized, we don't need to write much
code.

Programming and Problem-Solving 19


Types of Functions
• Library Functions: are the functions which are declared in
the C++ header files such as ceil(x), cos(x), exp(x), etc.

• User-defined functions: are the functions which are created


by the C++ programmer, so that he/she can use it many
times.
• It reduces complexity of a big program and optimizes the
code.

Programming and Problem-Solving 20


Declaration of a function
return_type function_name(data_type parameter...)
{
//code to be executed
}

Programming and Problem-Solving 21


Example of a function
#include <iostream>
using namespace std;
void func() { • Output
int i=0; • i=1 and j=1
int j=0; • i=1 and j=1
• i=1 and j=1
i++;
j++;
cout<<"i=" <<i<<" and j=" <<j<<endl;
}

int main(){
func();
func();
func(); Programming and Problem-Solving 22
Example of a function
• #include <iostream> • Output
• using namespace std;
• C=a+b 15
• void add(int a, int b) {
• int c=a+b;
• cout<<"C=a+b " <<c<<endl;
• }

• Int a, int b;
• Cin>>a;
• Cin>>b;
• int main(){

• add(a,b);

• }

Programming and Problem-Solving 23


GHANA COMMUNICATION TECHNOLOGY UNIVERSITY
DEPARTMENT OF COMPUTER SCIENCE

CSSD 101: Programming and Problem-Solving (Lecture 6)

By:

Gideon Owusu Agyeman


Tel: +233200340000 / +233546441122
Email: gideongenius@[Link] / me@[Link]
Website: [Link]

Programming and Problem solving 1


•Control Statement

Programming and Problem-Solving 2


If Statement
1.#include <iostream>
[Link] namespace std;
3.
4. int main () {
5. int num = 10;
6. if (num % 2 == 0)
7. {
8. cout<<"It is even number";
9. }
10. return 0;
11.}

Programming and Problem-Solving 3


C++ While loop
[Link](condition){
2.//code to be executed
3.}

Programming and Problem-Solving 4


1.#include <iostream>
[Link] namespace std;
[Link] main() {
4. int i=1;
5. while(i<=10)
6. {
7. cout<<i <<"\n"; // cout<<i <<endl;
8. i++;
9. }
10. }

Programming and Problem-Solving 5


C++ Do-While Loop
[Link]{
2.//code to be executed
3.}while(condition);

Programming and Problem-Solving 6


1.#include <iostream>
[Link] namespace std;
[Link] main() {
4. int i = 1;
5. do{
6. cout<<i<<"\n";
7. i++;
8. } while (i <= 10) ;
9.}

Programming and Problem-Solving 7


C++ For Loop
[Link](initialization; condition; incr/decr){
2.//code to be executed
3.}

Programming and Problem-Solving 8


1.#include <iostream>
[Link] namespace std;
[Link] main() {
4. for(int i=1;i<=10;i++){
5. cout<<i <<"\n";
6. }
7. }

Programming and Problem-Solving 9


C++ switch
1. switch(expression){
2. case value1:
3. //code to be executed;
4. break;
5. case value2:
6. //code to be executed;
7. break;
8. ......
9.
[Link]:
11. //code to be executed if all cases are not matched;
12. break;
13.}

Programming and Problem-Solving 10


1.#include <iostream>
[Link] namespace std;
[Link] main () {
4. int num;
5. cout<<"Enter a number to check grade:";
6. cin>>num;
7. switch (num)
8. {
9. case 90: cout<<"It is 90"; break;
10. case 80: cout<<"It is 80"; break;
11. case 70: cout<<"It is 70"; break;
12. default: cout<<"Not 90, 80 or 70"; break;
13. }
14. }

Programming and Problem-Solving 11


C++ Break Statement
• The C++ break is used to break loop or switch statement. It breaks the
current flow of the program at the given condition. In case of inner
loop, it breaks only inner loop.

[Link]-statement;
[Link];

Programming and Problem-Solving 12


C++ Break Statement
• #include <iostream> • Output
• using namespace std; • The number is 1
• int main (){ • The number is 2
• for(int i=1; i<=10; i++){ • The number is 3
• if(i==5){ • The number is 4
• break;
• }
• cout<<"The number is "<<i<<"\n";
• }
• }

Programming and Problem-Solving 13


C++ Continue Statement
• The C++ continue statement is used to continue loop. It continues the
current flow of the program and skips the remaining code at specified
condition. In case of inner loop, it continues only inner loop.

[Link]-statement;
[Link];

Programming and Problem-Solving 14


C++ Continue Statement
• #include <iostream> • Output
• using namespace std; • The number is 1
• int main (){ • The number is 2
• for(int i=1; i<=10; i++){ • The number is 3
• if(i==5){ • The number is 4
• continue; • The number is 6
• } • The number is 7
• cout<<"The number is "<<i<<"\n"; • The number is 8
• } • The number is 9
• The number is 10
•}

Programming and Problem-Solving 15


C++ Goto Statement
1. #include <iostream>
2. using namespace std;
3. int main()
• Output
4. {
• You are not eligible to vote!
5. ineligible:
• Enter your age:
6. cout<<"You are not eligible to vote!\n";
• 15
7. cout<<"Enter your age:\n";
• You are not eligible to vote!
8. int age;
• Enter your age:
9. cin>>age;
• 17
10. if (age < 18){ • You are not eligible to vote!
11. goto ineligible;
• Enter your age:
12. }
• 19
13. else
• You are eligible to vote!";
14. {
15. cout<<"You are eligible to vote!";
16. }
Programming and Problem-Solving 16
17.}
C++ Functions

Programming and Problem-Solving 17


C++ Functions
• The function in C++ language is also known as procedure or
subroutine in other programming languages.
• To perform any task, we can create function. A function can
be called many times. It provides modularity and code
reusability.

Programming and Problem-Solving 18


Advantage of functions in C++
• Code Reusability
• By creating functions in C++, you can call it many times. So
we don't need to write the same code again and again.
• Code optimization
• It makes the code optimized, we don't need to write much
code.

Programming and Problem-Solving 19


Types of Functions
• Library Functions: are the functions which are declared in
the C++ header files such as ceil(x), cos(x), exp(x), etc.

• User-defined functions: are the functions which are created


by the C++ programmer, so that he/she can use it many
times.
• It reduces complexity of a big program and optimizes the
code.

Programming and Problem-Solving 20


Declaration of a function
return_type function_name(data_type parameter...)
{
//code to be executed
}

Programming and Problem-Solving 21


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 ():

Programming and Problem-Solving 22


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:

Programming and Problem-Solving 23


Call a Function
• / Create a function
void myFunction() {
cout << "I just got executed!";
}

int main() {
myFunction(); // call the function
return 0;
}

// Outputs "I just got executed!"


Programming and Problem-Solving 24
• void myFunction() {
cout << "I just got executed!\n";
}
int main() {
myFunction();
myFunction();
myFunction();
return 0;
}
// I just got executed!
// I just got executed!
// I just got executed!

Programming and Problem-Solving 25


• // Function declaration
void myFunction();
// The main method
int main() {
myFunction(); // call the function
return 0;
}
// Function definition
void myFunction() {
cout << "I just got executed!";
}

Programming and Problem-Solving 26


Example of a function
#include <iostream>
using namespace std;
void func() {
int i=0;
• Output
int j=0; • i=1 and j=1
i++;
j++;
• i=1 and j=1
cout<<"i=" <<i<<" and j=" <<j<<endl; • i=1 and j=1
}

int main(){
func();
func();
func(); Programming and Problem-Solving 27
Example of a function
• #include <iostream> • Output
• using namespace std;
• C=a+b 15
• void add(int a, int b) {
• int c=a+b;
• cout<<"C=a+b " <<c<<endl;
• }

• Int a, int b;
• Cin>>a;
• Cin>>b;
• int main(){

• add(a,b);

• }

Programming and Problem-Solving 28


C++ Function Parameters
• 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 functionName(parameter1, parameter2, parameter3) {


// code to be executed
}

Programming and Problem-Solving 29


• void myFunction(string fname) {
cout << fname << " Genius\n";
}
int main() {
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}
// Liam Genius
// Jenny Genius
// Anja Genius

Programming and Problem-Solving 30


Function Overloading
• With function overloading, multiple functions can
have the same name with different parameters:

Programming and Problem-Solving 31


Function Overloading
• int myFunction(int x)
float myFunction(float x)
double myFunction(double x, double y)

Programming and Problem-Solving 32


Function Overloading
• int plusFuncInt(int x, int y) {
return x + y;
}
double plusFuncDouble(double x, double y) {
return x + y;
}
int main() {
int myNum1 = plusFuncInt(8, 5);
double myNum2 = plusFuncDouble(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}
Programming and Problem-Solving 33
Function Overloading
int plusFunc(int x, int y) {
return x + y;
}
double plusFunc(double x, double y) {
return x + y;
}
int main() {
int myNum1 = plusFunc(8, 5);
double myNum2 = plusFunc(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}
Programming and Problem-Solving 34
Recursion
• Recursion is the technique of making a function call
itself. This technique provides a way to break
complicated problems down into simple problems which
are easier to solve.
• Recursion may be a bit difficult to understand. The best
way to figure out how it works is to experiment with it.

Programming and Problem-Solving 35


Recursion
• Recursion is the technique of making a function call
itself. This technique provides a way to break
complicated problems down into simple problems which
are easier to solve.
• Recursion may be a bit difficult to understand. The best
way to figure out how it works is to experiment with it.

• Read more about it

Programming and Problem-Solving 36


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:

Programming and Problem-Solving 37


C++ Arrays
• 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];
• string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
• int myNum[3] = {10, 20, 30};

Programming and Problem-Solving 38


Access the Elements of an Array
You access an array element by referring to the index number
inside square brackets [].
This statement accesses the value of the first
element in cars:

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


cout << cars[0];
// Outputs Volvo

Programming and Problem-Solving 39


Change an Array Element
• To change the value of a specific element, refer to the index
number:
• string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
cout << cars[0];
// Now outputs Opel instead of Volvo

Programming and Problem-Solving 40


Omit Array Size
• In C++, you don't have to specify the size of the array.
The compiler is smart enough to determine the size of
the array based on the number of inserted values:

• string cars[] = {"Volvo", "BMW", "Ford"}; // Three


array elements
• Same as
• string cars[3] = {"Volvo", "BMW", "Ford"}; // Also
three array elements

Programming and Problem-Solving 41


Omit Elements on Declaration
• It is also possible to declare an array without
specifying the elements on declaration, and add
them later:

string cars[5];
cars[0] = "Volvo";
cars[1] = "BMW";

Programming and Problem-Solving 42


Multi-Dimensional Arrays
• A multi-dimensional array is an array of arrays.
• To declare a multi-dimensional array, define the
variable type, specify the name of the array
followed by square brackets which specify how
many elements the main array has, followed by
another set of square brackets which indicates
how many elements the sub-arrays have:
• string letters[2][4];

Programming and Problem-Solving 43


Multi-Dimensional Arrays
• As with ordinary arrays, you can insert values
with an array literal - a comma-separated list
inside curly braces. In a multi-dimensional array,
each element in an array literal is another array
literal.
• string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
Programming and Problem-Solving 44
Multi-Dimensional Arrays
• Each set of square brackets in an array declaration adds
another dimension to an array. An array like the one above is said to have
two dimensions.
• Arrays can have any number of dimensions. The more dimensions an array
has, the more complex the code becomes. The following array has three
dimensions:
• string letters[2][2][2] = {
{
{ "A", "B" },
{ "C", "D" }
},
{
{ "E", "F" },
{ "G", "H" }
}
};

Programming and Problem-Solving 45


Access the Elements of a Multi-
Dimensional Array
• To access an element of a multi-dimensional array, specify an index number in
each of the array's dimensions.
• This statement accesses the value of the element in the first row
(0) and third column (2) of the letters array.

• string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};

cout << letters[0][2]; // Outputs "C"


Programming and Problem-Solving 46
Change Elements in a Multi-Dimensional
Array
• To change the value of an element, refer to the
index number of the element in each of the
dimensions:
• string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
letters[0][0] = "Z";

cout << letters[0][0]; // Now outputs "Z"


instead of "A" Programming and Problem-Solving 47
Programming and Problem-Solving 48
Programming and Problem-Solving 49
GHANA COMMUNICATION TECHNOLOGY UNIVERSITY
DEPARTMENT OF COMPUTER SCIENCE

CSSD 101: Programming and Problem-Solving (Lecture 7)

By:

Gideon Owusu Agyeman


Tel: +233200340000 / +233546441122
Email: gideongenius@[Link] / me@[Link]
Website: [Link]

Programming and Problem solving 1


C++ What is OOP?
• OOP stands for Object-Oriented Programming.
• Procedural programming is about writing procedures or functions that perform
operations on the data, while object-oriented programming is about creating objects
that contain both data and functions.
• Object-oriented programming has several advantages over procedural programming:
• OOP is faster and easier to execute
• OOP provides a clear structure for the programs
• OOP helps to keep the C++ code DRY "Don't Repeat Yourself", and makes the code
easier to maintain, modify and debug
• OOP makes it possible to create full reusable applications with less code and shorter
development time
• Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of
code. You should extract out the codes that are common for the application, and place
them at a single place and reuse them instead of repeating it.

Programming and Problem-Solving 2


C++ What are Classes and Objects?
• Classes and objects are the two main aspects of object-
oriented programming.
• Class – Fruit
• Objects
• Mango, Apple, Pineapple etc

• Class - Car
• Objects
• Honda, BMW, Volvo etc

Programming and Problem-Solving 3


C++ What are Classes and Objects?
• So, a class is a template for objects, and an object is an
instance of a class.
• When the individual objects are created, they inherit all
the variables and functions from the class.

Programming and Problem-Solving 4


C++ Classes/Objects
• Everything in C++ is associated with classes and
objects, along with its attributes and methods. For
example: in real life, a car is an object. The car
has attributes, such as weight and color,
and methods, such as drive and brake.
• Attributes and methods are
basically variables and functions that belongs to the
class. These are often referred to as "class members".
• A class is a user-defined data type that we can use in
our program, and it works as an object constructor, or a
"blueprint" for creating objects.

Programming and Problem-Solving 5


Create a Class
• To create a class use the keyword class

• class MyClass { // The class


public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};

Programming and Problem-Solving 6


Example explained

•The class keyword is used to create a class called MyClass.


•The public keyword is an access specifier, which specifies
that members (attributes and methods)
of the class are accessible from outside the class.
•Inside the class, there is an integer variable myNum and a
string variable myString. When variables are declared
within a class, they are called attributes.
•At last, end the class definition with a semicolon ;.

Programming and Problem-Solving 7


Create an Object

• In C++, an object is created from a class. We have


already created the class named MyClass, so now
we can use this to create objects.
• To create an object of MyClass, specify the class
name, followed by the object name.
• To access the class attributes (myNum and myString),
use the dot syntax (.) on the object:

Programming and Problem-Solving 8


• class MyClass { // The class • Output
public: // Access specifier • 15
int myNum; // Attribute (int
variable) • Some text
string myString; // Attribute (string
variable)
};
int main() {
MyClass myObj; // Create an object of MyClass
// Access attributes and set values
[Link] = 15;
[Link] = "Some text";
// Print attribute values
cout << [Link] << "\n";
cout << [Link];
return 0;
}

Programming and Problem-Solving 9


1. #include <iostream>
2. using namespace std;
3. class Student {
4. public:
5. int id; //data member (also instance variable)
6. string name; //data member(also instance variable)
7. };
8. int main() {
9. Student s1; //creating an object of Student
10. [Link] = 201;
11. [Link] = "Sonoo Jaiswal";
12. cout<<[Link]<<endl;
13. cout<<[Link]<<endl;
14. return 0;
15.}

Programming and Problem-Solving 10


C++ Class Methods
Methods are functions that belongs to the class.
There are two ways to define functions that belongs
to a class:
•Inside class definition
•Outside class definition
In the following example, we define a function inside
the class, and we name it "myMethod".

Note: You access methods just like you access


attributes; by creating an object of the class and
using the dot syntax (.): Programming and Problem-Solving 11
Inside a class example
• class MyClass { // The class
public: // Access specifier
void myMethod() { // Method/function defined
inside the class
cout << "Hello World!";
}
};
int main() {
MyClass myObj; // Create an object of MyClass
[Link](); // Call the method
return 0;
}

Programming and Problem-Solving 12


Outside a class example
• class MyClass { // The class
public: // Access specifier
void myMethod(); // Method/function declaration
};
// Method/function definition outside the class
void MyClass::myMethod() {
cout << "Hello World!";
}
int main() {
MyClass myObj; // Create an object of MyClass
[Link](); // Call the method
return 0;
}
Programming and Problem-Solving 13
Outside a class example - parameters
• #include <iostream>
using namespace std;
class Car {
public:
int speed(int maxSpeed);
};
int Car::speed(int maxSpeed) {
return maxSpeed;
}
int main() {
Car myObj; // Create an object of Car
cout << [Link](200); // Call the method with an argument
return 0;
}

Programming and Problem-Solving 14


Constructors

• A constructor in C++ is a special


method that is automatically called when an
object of a class is created.

• To create a constructor, use the same name


as the class, followed by parentheses ():

Programming and Problem-Solving 15


Constructors
• class MyClass { // The class
public: // Access specifier
MyClass() { // Constructor
cout << "Hello World!";
}
};

int main() {
MyClass myObj; // Create an object of MyClass (this will
call the constructor)
return 0;
}
Programming and Problem-Solving 16
• class Car { // The class • int main() {
public: // Access // Create Car objects and call the
specifier constructor with different values
string brand; // Attribute Car carObj1("BMW", "X5", 1999);
string model; // Attribute Car
int year; // Attribute carObj2("Ford", "Mustang", 1969);
Car(string x, string
y, int z) { // Constructor with // Print values
parameters cout<<[Link]<<" "<<
brand = x; [Link] << " " <<
model = y; [Link] << "\n";
year = z;
} cout << [Link] <<" "<<
}; [Link] << " " <<
[Link] << "\n";
return 0;
}

Programming and Problem-Solving 17


Access Specifiers
The public keyword is an access specifier. Access specifiers
define how the members (attributes and methods) of a class can
be accessed. In the example above, the members are public -
which means that they can be accessed and modified from outside
the code.
However, what if we want members to be private and hidden from
the outside world?
In C++, there are three access specifiers:
•public - members are accessible from outside the class
•private - members cannot be accessed (or viewed) from outside
the class
•protected - members cannot be accessed from outside the class,
however, they can be accessed in inherited classes.

Programming and Problem-Solving 18


Example
• class MyClass {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};
int main() {
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private) Error
return 0;
}

Programming and Problem-Solving 19


Encapsulation
• The meaning of Encapsulation, is to make sure
that "sensitive" data is hidden from users.

• To achieve this, you must declare class


variables/attributes as private (cannot be accessed
from outside the class).
• If you want others to read or modify the value of a
private member, you can provide public get and
set methods.
Programming and Problem-Solving 20
Encapsulation - Access Private Members
• #include <iostream> • int main() {
using namespace std; Employee myObj;
[Link](50000);
class Employee { cout << [Link]();
private: return 0;
// Private attribute }
int salary;
public:
// Setter
void setSalary(int s) {
salary = s;
}
// Getter
int getSalary() {
return salary;
}
};

Programming and Problem-Solving 21


Example explained

• The salary attribute is private, which have restricted


access.
• The public setSalary() method takes a parameter (s)
and assigns it to the salary attribute (salary = s).
• The public getSalary() method returns the value of
the private salary attribute.
• Inside main(), we create an object of the Employee class.
• Now we can use the setSalary() method to set the value
of the private attribute to 50000.
• Then we call the getSalary() method on the object to
return the value. Programming and Problem-Solving 22
Why Encapsulation?

• It is considered good practice to declare your class


attributes as private (as often as you can).
Encapsulation ensures better control of your data,
because you (or others) can change one part of the
code without affecting other parts

• Increased security of data

Programming and Problem-Solving 23


C++ Inheritance
In C++, it is possible to inherit attributes and methods
from one class to another. We group the "inheritance
concept" into two categories:
• derived class (child) - the class that inherits from
another class
• base class (parent) - the class being inherited from

• To inherit from a class, use the : symbol.

• In the example below, the Car class (child) inherits the


attributes and methods from the Vehicle class (parent):
Programming and Problem-Solving 24
Inheritance

• // Base class
class Vehicle {
public: int main() {
string brand = “Honda"; Car myCar;

void fun() { [Link]();


cout << “We are having
fun! \n" ; cout << [Link] + " " +
} [Link];
};
// Derived class return 0;
class Car: public Vehicle { }
public:
string model = “Civic";
};
Programming and Problem-Solving 25
Multilevel Inheritance
• A class can also be derived from one
class, which is already derived from
another class.

• In the following example, MyGrandChild is


derived from class MyChild (which is
derived from MyClass).
Programming and Problem-Solving 26
Multilevel Inheritance
• // Base class (parent) •
class MyClass { int main() {
public:
void myFunction() { MyGrandChild myObj;
cout << "Some content in parent [Link]();
class." ; return 0;
} }
};
// Derived class (child)
class MyChild: public MyClass {

};
// Derived class (grandchild)
class MyGrandChild: public MyChild {

};

Programming and Problem-Solving 27


Multiple Inheritance
A class can also be derived from more than one base class, using a comma-separated list:

• // Base class
class MyClass { • // Derived class
public: class MyChildClass: public MyClass, public MyOth
void myFunction() {
erClass {
cout << "Some content in parent class.";
} };
};

// Another base class int main() {


class MyOtherClass { MyChildClass myObj;
public: [Link]();
void myOtherFunction() { [Link]();
return 0;
cout << "Some content in another }
class." ;
}
};

Programming and Problem-Solving 28


Inheritance Access

You learned from the Access Specifiers chapter that


there are three specifiers available in C++. Until now,
we have only used public (members of a class are
accessible from outside the class) and private
(members can only be accessed within the class).

The third specifier, protected, is similar to private,


but it can also be accessed in the inherited class:
Programming and Problem-Solving 29
Polymorphism
Polymorphism means "many forms", and it occurs
when we have many classes that are related to
each other by inheritance.
• Like we specified in the previous
slides; inheritance lets us inherit attributes and
methods from another class.
• Polymorphism uses those methods to perform
different tasks. This allows us to perform a single
action in different ways.
Programming and Problem-Solving 30
Polymorphism
• // Base class
class Animal { •
public:
void animalSound() { int main() {
cout << "The animal makes a sound \n";
} Animal myAnimal;
};
Pig myPig;
// Derived class
class Pig : public Animal { Dog myDog;
public:
void animalSound() {
cout << "The pig says: wee wee \n";
}
}; [Link]();
// Derived class [Link]();
class Dog : public Animal {
public: [Link]();
void animalSound() {
cout << "The dog says: bow wow \n"; return 0;
}
}; }

Programming and Problem-Solving 31


C++ Files

The fstream library allows us to work with files.


To use the fstream library, include both the
standard <iostream> AND the <fstream> header file:

Example
#include <iostream>
#include <fstream>

Programming and Problem-Solving 32


C++ Files
• There are three classes included in the fstream library,
which are used to create, write or read files:

Programming and Problem-Solving 33


Create and Write To a File
To create a file, use either the ofstream or fstream class, and specify the name of the file.
To write to the file, use the insertion operator (<<).

#include <iostream>
#include <fstream>
using namespace std;

int main() {
// Create and open a text file
ofstream MyFile("[Link]");

// Write to the file


MyFile << “This is the first line”;

// Close the file


[Link](); //It is considered good practice, and it can clean up unnecessary memory space.
} Programming and Problem-Solving 34
Create and Write To a File

To read from a file, use either


the ifstream or fstream class, and the name of
the file.

Note that we also use a while loop together with


the getline() function (which belongs to
the ifstream class) to read the file line by line,
and to print the content of the file.

Programming and Problem-Solving 35


Create and Write To a File
// Create a text string, which is used to output the text file
string myText;

// Read from the text file


ifstream MyReadFile("[Link]");
// Use a while loop together with the getline() function to read the file line by line
while (getline (MyReadFile, myText)) {
// Output the text from the file
cout << myText;
}

// Close the file


[Link]();
Programming and Problem-Solving 36
Thank you
• Prepare for your mid-semester exams
• Assignment will be given to you

Programming and Problem-Solving 37

You might also like