10 Comp Notes
10 Comp Notes
for Grade X
According to New Syllabus – Sindh Textbook Board(STBB)
Table of Contents
0 CONTENTS
0 Contents ......................................................................................................................... i
1 PROBLEM SOLVING AND ALGORITHM DESIGNING .......................................................... 1
1.1 Problem Solving ..................................................................................................... 1
1.1.1 Problem Solving Process:.................................................................................... 1
1.1.2 Problem Solving Example Related to Real Life: ..................................................... 1
1.1.3 Problem Solving Example Related to Computer Programming: ............................. 2
1.2 Algorithm ............................................................................................................... 3
1.2.1 Use of Algorithm in Problem Solving .................................................................... 3
1.2.2 Qualities of a Good Algorithm.............................................................................. 3
1.2.3 Examples of Algorithm ........................................................................................ 4
1.3 Flowchart ............................................................................................................... 6
1.3.1 Use of Flowchart in Problem Solving .................................................................... 6
1.4 Data Structure ........................................................................................................ 8
1.4.1 Linear Data Structures ........................................................................................ 8
1.4.2 Non-linear Data Structures ............................................................................... 11
2 BASICS OF PROGRAMMING IN C++ ............................................................................... 14
2.1 Computer Program ............................................................................................... 14
2.1.1 Syntax: ............................................................................................................. 14
2.1.2 Programming Language: ................................................................................... 15
2.1.3 Language Translator: ........................................................................................ 18
2.1.4 Errors: .............................................................................................................. 20
2.2 Integrated Development Environment ................................................................... 21
2.2.1 Benefits of IDE .................................................................................................. 21
2.2.2 Components of IDE........................................................................................... 21
2.3 C++ Programming Language ................................................................................. 22
2.3.1 Reserved words ................................................................................................ 23
2.3.2 Data Types ....................................................................................................... 24
2.3.3 Identifier: Constant and Variable ....................................................................... 24
2.3.4 String in C++ ..................................................................................................... 26
3 INPUT/OUTPUT HANDLING IN C++ ................................................................................ 27
3.1 Basic Structure of C++ .......................................................................................... 27
Problem:
“A situation or task that requires a solution, typically involving data processing,
analysis, or decision-making to meet certain requirements or achieve a desired
outcome is called a problem.”
Example:
Example:
• Solution 1: Jump-start the car using jumper cables and another car.
• Solution 3: Check if the battery terminals are corroded and clean them.
Analyze the advantages and disadvantages of each solution, and pick the best
one based on factors like efficiency and simplicity.
Example:
• Solution 2: replace battery is more expensive and only necessary if the battery is
fully dead.
• Solution 3: clean terminals is simple and might solve the problem if corrosion is the
issue.
Choose Solution 1 (jump-start) first, as it’s quick and might resolve the issue without
major effort.
Example:
Use jumper cables to connect to another car and start your vehicle. Once started, let it
run to charge the battery. Afterward, monitor the battery’s performance to see if it holds
a charge.
Example: A student needs to write a program to calculate the total price of items in a
shopping cart.
Example:
• Solution 1: Write a simple program using a loop to add the price of each item.
• Solution 2: Use an in-built function to calculate the total from a list of prices.
Analyze the pros and cons of each solution, and pick the best one based on
factors like efficiency and simplicity.
Example:
• Solution 1 (loop): Suitable for beginners but may take more time.
Example:
The student writes the program using an in-built function and tests it with different
shopping cart values to ensure the total price is calculated correctly.
1.2 ALGORITHM
“A step-by-step procedure or set of rules designed to perform a specific task or
solve a particular problem is called algorithm.”
2. Efficiency:
Well-designed algorithms improve the usage of resource, such as time and memory,
leading to faster and more efficient programs.
3. Problem Breakdown:
Algorithms help break complex problems into smaller, manageable tasks, making it
easier to implement solutions systematically.
2. Efficiency:
The algorithm should make the best use of resources, such as time and memory. It
should run quickly and use minimal space.
3. Simplicity:
A simple algorithm is easier to understand, implement, and maintain. It should avoid
the actual computer code.
4. Generality:
A good algorithm should be applicable to a wide range of problems, not just one specific
case. It should work for different inputs and situations.
5. Show the Result: Tell the user the total (the sum).
5. Multiply Length, Width, and Height: Combine these measurements to find out how
much space is inside the box.
6. Show the Result: Tell the user the volume of the box.
2. Get the Total Amount: Ask for the total number (this is the whole).
3. Get the Part Amount: Ask for the part of the total you want to find the percentage for.
4. Divide the Part by the Total: Find how much of the total the part is.
1. Define the Problem: The car won’t start, indicating a potential battery issue.
2. Check Battery Terminals: Inspect the terminals for corrosion and ensure they are
tightly connected.
4. Jump-Start the Battery: Connect jumper cables to a working vehicle and try starting the
car.
5. Check for Corrosion: If jump-starting works, clean terminals and check for further
issues.
6. Follow Up: Monitor the battery's performance over the next few days.
1. Define the Problem: Calculate the total price of items in a shopping cart.
4. Sum Prices: Iterate through the list of prices and add each price to the total.
1.3 FLOWCHART
“A graphical representation of step-by-step instructions in a sequence to describe a
computer program using shapes and objects is called flowchart.”
1. Start/Stop (Oval)
2. Flow Path (Arrows)
3. Input/Output (Parallelogram)
4. Process (Rectangle)
5. Decision/Condition (Diamond)
Flowcharts provide a clear and visual way to represent complex processes that helps
programmers understand the sequence of step-by-step instructions.
2. Simplification of Processes:
By breaking down a problem into smaller steps, flowcharts make it easier to identify and
analyze each part of the process that helps in understanding the overall problem more
clearly.
3. Easy to Understand:
Flowcharts use standard symbols and shapes, making them easy to read and
comprehend.
Flowchart Algorithm
A flowchart is a visual representation of a An algorithm is a step-by-step procedure or set of
process or algorithm using symbols and arrows. rules for solving a problem.
Flowcharts use shapes (like ovals, rectangles, Algorithms are usually written in plain language or
diamonds) connected by arrows to show the pseudocode, listing steps in a sequential manner.
flow of steps.
Flowcharts help visualize the sequence of Algorithms provide a clear, logical approach to
actions and decisions, making complex problem-solving, outlining exactly what needs to
processes easier to understand. be done without visualization.
Flowcharts are often used for presentations and Algorithms are used primarily in programming and
to explain processes visually to others. software development to plan and implement
solutions.
Data structures define how data is arranged in memory and how it can be manipulated for
various operations like insertion, deletion, searching, and sorting.
Data structures are mainly classified into two types: linear and non-linear.
In these structures, each element is connected to its previous and next element, forming a
linear sequence.
Stack:
“A linear data structure that works with a specific order for adding and removing
items at only one end is called stack.”
It follows a specific order for adding and removing items known as LIFO (Last In, First Out) like a
real-world stack of items, such as a stack of books or plates.
The last item added to the stack is the first one to be removed. Imagine stacking plates—
when you add a new plate, you place it on top. When you remove one, you take the plate
from the top.
2. Push Operation:
Adding an item to the stack is termed as push. The new item is always placed on top of
the stack.
3. Pop Operation:
Removing an item from the stack is termed as pop. You can only remove the item from
the top of the stack.
4. Stack overflow:
If the stack is already full, it will return an overflow error which means no more items
can be added.
5. Stack underflow:
If the stack is already empty, it will return an underflow error which means no more
items can be removed.
Queue:
“A linear data structure that follows a particular order in which the items are
added from one end and removed from the another is called queue.”
It follows a FIFO (First In, First Out) order which works like a real-life queue (line) of people
waiting for something, like in a ticket line or at a grocery store.
The first item added to the queue is the first one to be removed. Think of a line of people:
the person who enters the line first is the first to leave.
2. Enqueue Operation:
Adding an item to the queue is termed as enqueue operation. The new item is always
added to the back of the queue.
3. Dequeue Operation:
Removing an item from the queue is called dequeue operation. You can only remove
the item from the front of the queue.
o The rear of the queue is where new items are added (enqueued).
Array:
“A linear data structure which holds a list of finite data elements of same data
type, and each element of array is referenced by a set of index of consecutive
numbers is called array.”
Think of an array like a row of lockers, where each locker (or slot) holds one item, and each item
can be accessed by its position (index) in the array.
1. Fixed Size:
Once an array is created, it has a fixed number of slots (or spaces), and you cannot
change the size. For example, if you create an array of 6 elements, it will always hold 6
elements.
For example, if you create an array to store numbers, all the elements must be
numbers; if it's for names, all elements must be strings (text).
3. Indexing:
Each element in an array has a position number called an index. The first element is at
position 0, the second at position 1, and so on.
4. Efficient Access:
Any element can be quickly accessed by using its index number, making it easy to find
and use specific data from the array.
Tree:
“A hierarchical non-linear data structure that consists of nodes connected by
edges is called tree.”
It resembles an upside-down tree, with a single root at the top and branches spreading
downwards.
Each node can have multiple child nodes but only one parent node (except for the root, which
has no parent).
1. Root Node:
The top node of the tree, from which all other nodes descend.
2. Parent Node:
Each node (except the root) is a parent of the nodes connected to it below.
3. Child Node:
Each node that is descendant of another node is called child of that node.
4. Edge:
Link connecting two nodes.
Binary Tree
“A tree where each node has at most two children (known as left child and right
child) is known as a binary tree.”
General Tree
“A tree that contains any number of subtrees is known as a general tree.”
Graph:
“A collection of nodes (or vertices) connected by edges is called a graph.”
Unlike trees, graphs can have cycles (where it can return to the same node by following edges)
and do not have a strict hierarchical structure.
1. Vertices (Nodes):
The points in a graph that represent entities.
2. Edges:
The connections between the vertices that can represent relationships.
“A type of graph that contains directed edges, that means its edges are pointing
in a particular direction is known as directed graph.”
“A type of graph that does not contain any direction associated with its nodes,
that means its edges are non-directional is known as undirected graph.”
Queue follows FIFO (First In, First Out). Stack follows LIFO (Last In, First Out).
It uses Enqueue (add to rear) and Dequeue It uses Push (add to top) and Pop (remove
(remove from front). from top).
It can access the front item directly. It can access only the top item directly.
Tree Graph
Tree is a hierarchical data structure with a Graph can have any arrangement of nodes,
single root node. including cycles.
Each node has one parent and can have Nodes can be connected to any number of
multiple children. other nodes.
Tree is always directed (parent to child). Graph can be directed or undirected.
It cannot have cycles (looping back to the It can have cycles (returning to the same
same node is not allowed). node is possible).
A computer program contains data and instruction which involves understanding fundamental
concepts in any programming language. The fundamental concepts are:
1. Data Types
2. Constants and Variables
3. Arrays and Strings
4. Input and Output Streams
5. Operators
6. Control Structures
7. Functions
In any programming language, there are keywords (or reserved words) for program statements
that is combined with a set of rules called syntax.
2.1.1 Syntax:
“The set of rules that define the structure of statements or instructions in a
programming language is called syntax.”
Importance of Syntax:
4. Syntax ensures the correct structure of code, which is crucial in any programming
language, allowing it to be understood by the compiler and executed by the machine.
5. Syntax provides the precise instructions for the language translation process.
6. Without proper syntax, the program cannot function correctly causing errors.
1. Low-Level Language
“A type of programming language that is very close to machine code or
assembly language which directly interacts with a computer’s hardware.”
Assembly Language:
Mnemonic codes to represent machine instructions.
Mnemonic Notations
2. Mid-Level Language
“A type of programming language that provides a balance between low-level and
high-level language by offering abstraction from machine code as well as direct
interaction with a computer’s hardware.”
3. High-Level Language
“A type of programming language that is designed to be more human readable
and closer to natural languages, allowing to focus on problem solving rather
than managing hardware resources.”
Python: It is famous for its simplicity which is easily used by programmers in Artificial
Intelligence (AI), machine learning, and automation.
C#: It is primarily used for Windows applications, game development (Unity), and
enterprise solutions.
Machine Code: Binary code that the process in computer system can directly execute.
Roles of Translator
1. It converts high-level source code into machine code so that the computer’s hardware
(CPU) can understand and execute the instructions.
2. Translators detect and report syntax errors during the translation process.
3. Translators allow programmers to write in human-readable languages, which are easier
to develop and maintain.
Types of Translators
1. Compiler
“A language translator that is used to convert the source code written in high-
level language into an executable machine code file such as .exe is called
compiler.”
2. Interpreter
“A language translator that is used to read each line of code, translates it into
machine code, and immediately executes it, stopping when it encounters an
error is called interpreter.”
3. Assembler
“A language translator that reads assembly language code and converts it into
machine code that the processor can execute directly is called assembler.”
Compiler Interpreter
1. Compiler translates the entire source
1. Interpreter translates and executes
code into machine code at once
the source code line by line.
before execution.
2. It has generally faster execution as 2. It has slower execution since each
the entire code is compiled into line is translated and executed one at
machine code beforehand. a time.
3. It detects and reports errors for entire 3. It stops at the first error it encounters
code after compilation. and reports errors line by line.
2.1.4 Errors:
“An issue or problem in the code that causes the program to fail during
compilation or execution, causes unexpected results, or lead to the program
crashing is called an error.”
1. Syntax Error
“The programming error that occurs when the code violates the rules or
grammar of the programming language is called syntax error.”
Syntax error is detected by the compiler. If there are any syntax errors during compilation, the
program will not compile. Examples:
2. Run-time Error
“The programming error that occurs during program execution (run-time) after
successful compilation is called run-time error.”
1. Division by zero
2. Accessing invalid memory.
3. Array out of bounds
3. Logical Error
“The programming error that occurs when the program compiles and runs but it
produces incorrect or unintended results is called logical error.”
2. Compiler:
The compiler translates the source code written in a high-level language into machine
language forming an executable machine code file in .exe.
3. Debugger:
The debugger helps in finding and fixing errors in the program, allowing programmers to
inspect their code step by step.
4. Linker:
The linker opens the compiled program file and links it with the referenced library files
as needed.
5. Loader:
The loaded loads the executable file into computer’s memory and initiates the
processing of the instructions in the CPU.
Literals: Fixed values in the source code such as numbers, characters, and strings.
Understanding and using these keywords effectively is essential for writing efficient and robust
C++ programs.
Keyword Description
int Defines an integer data type.
float Defines a floating-point number.
double Defines a double-precision floating-point number.
char Defines a single character.
void Specifies that a function does not return any value.
bool Defines a Boolean value (true or false).
if Starts a conditional statement.
else Specifies an alternative branch of an if statement.
switch Allows selection between multiple options.
case Defines a case in a switch statement.
for Starts a loop that repeats a block of code a specific number of times.
while Starts a loop that repeats a block of code as long as a condition is true.
do Starts a do-while loop, where the condition is checked after the block of code is
executed.
return Exits a function and optionally returns a value.
break Exits a loop or switch statement prematurely.
continue Skips the remaining code in the current iteration of a loop and proceeds with the next
iteration.
const Declares a constant value that cannot be changed.
namespace Defines a scope for identifiers to avoid naming conflicts.
TRUE Represents the Boolean value true.
FALSE Represents the Boolean value false.
These are the fundamental data types built into the language:
Constant:
“A data item whose value cannot change during the execution of the program is
called constant.”
1. Literal constant
2. Defined constant
Literal constants can be numbers, characters, strings, or any other data type that directly
encodes the data into the source code:
Defined Constant:
“A named identifier that allows programmer to assign a name to a literal
constant at the beginning of the source code is called defined constant.”
Defined constants are named and needed to be declared in the source code which can be done
in two ways:
1. Using #define
It allows the programmer to define constant without specifying the data type.
2. Using const
It requires declaration of the data type of the constant before assigning the literal.
Variable:
“A named identifier that allows programmer to assign a name to a value which
can change throughout the execution of a program is called a variable.”
Variables are used to store data that can be accessed and manipulated by the program.
Variable Declaration
“When an identifier is created by the compiler with a specific name and data
type in the program, it is called variable declaration.”
It reserves memory for that variable but does not assign any initial value.
For assigning or input marks to a variable, it can be declared with an integer data type and a
unique name.
Variable Initialization
“When a variable is declared with a specific name and data type in the program,
assigning an initial value to the variable is called variable initialization.”
It also can be performed at the time of declaration as well as after the declaration.
Variable Assignment
“Changing the value stored in an already declared variable, is called variable
assignment.”
A variable can be declared with string data type just like any other data type.
A string can be initialized with a string literal or by user input.
It requires <string.h> function header.
8. Pre-processor Directives
9. Main Function Header
10. Body of the program
#include <iostream>
This part contains #include or #define statements that are processed before compilation of
code begins, which allows to include libraries such as <iostream> library for input and output
operations.
int main()
The return type of main() or main(void) is integer int which means that it returns an
integer value to indicate success or failure when the program exits on return.
The beginning of the body of the program” or main function is represented by opening curly
braces.
The ending of the body of the program or main function is represented by opening curly braces.
statement;
These are instructions that perform particular task and ended using statement terminator ;
return 0;
The return statement at the end of the body of main function indicates the program has
finished successfully. By convention, a return value of 0 means the program executed
successfully.
1. Single-line comments
2. Multi-line comments
Single-line comments begin with // and extend to the end of the line.
Everything after // on that line is considered a comment and is ignored by the compiler.
OUTPUT
Multi-line comments begin with /* and end with */. They can span multiple lines.
Everything between /* and */ is considered a comment and is ignored by the compiler.
OUTPUT
C++ offers a variety of libraries for handling input and output operations. However, <iostream>
is the most commonly used library in C++ for console input/output operations.
<iostream> provides objects like cin>> and cout<< for input/output operations.
<stdio.h>
The primary library for handling standard input/output (I/O) operations. Functions in <stdio.h>
include:
<conio.h>
It provides console I/O functions but is non-standard and used in some environments (like
Turbo C++). Functions include
1. getch()
2. getche()
3. clrscr()
It is generally not available in modern compiler like DevC++ and does not provide direct output
functions similar to printf() or cout<<.
Output Description
Statements
cout<<
puts()
C Library:
<cstdio>
OR OUTPUT
<stdio.h>
printf()
C Library:
<cstdio>
OR OUTPUT
<stdio.h>
There is no output stream for <conio.h>. It does not feature in modern compiler like DevC++
but it can be used with old compiler like Turbo C++ or Borland C++.
Input Description
Statements
cin>>
C++ Library:
<iostream>
OUTPUT
Input Description
Statements
getch() The getch() reads a character without displaying it.
C Library:
<conio.h>
OUTPUT
C Library:
<conio.h>
OUTPUT
getchar() getchar() reads a single character and waits for the user to press Enter.
C Library:
<cstdio>
OR
<stdio.h>
OUTPUT
C Library:
<cstdio>
OR
<stdio.h>
OUTPUT
3.4 OPERATORS:
“A symbol that performs specific function on variable and values is called
operator.”
1. Arithmetic Operator
2. Relational Operator
3. Assignment Operator
4. Increment Operator
5. Decrement Operator
6. Logical Operator
7. Arithmetic Assignment Operator
1. Addition Syntax: a + b
2. Subtraction Syntax: a – b
“An arithmetic operator which subtracts right operand from the left is known as
subtraction operator.”
3. Multiplication Syntax: a * b
4. Division Syntax: a / b
“An arithmetic operator which divides the left operand by the right operand is
known as division operator.”
5. Modulus Syntax: a % b
“An arithmetic operator which returns the remainder of the division of the left
operand by the right operand is known as modulus operator.”
1. Equal to Syntax: a == b
“A relational operator that checks if the values of both operands are equal is
known as equal to operator.”
“A relational operator that checks if the values of both operands are not equal is
known as not equal to operator.”
“A relational operator that checks if the left operand value is greater than the
right is known as greater than operator.”
“A relational operator that checks if the left operand value is less than the right is
known as less than operator.”
“A relational operator that checks if the left operand value is greater than or
equal to the value of the right operand is known as greater than or equal to
operator.”
“A relational operator that checks if the left operand value is less than or equal
to the value of the right operand is known as less than or equal to operator.”
“Such increment operator that increases the value of the operand by 1 before
using its value.”
“Such increment operator that increases the value of the operand by 1 after
using its value.”
“Such decrement operator that decreases the value of the operand by 1 before
using its value.”
“Such decrement operator that decreases the value of the operand by 1 after
using its value.”
“Such logical operator which returns true if all relational expressions are true,
else it returns false, is called AND operator.”
“Such logical operator which returns true if either one of the relational
expressions is true, else it returns false, is called OR operator.”
“Such operator which adds two operands and assigns the value to left operand.”
a += b OR a=a+b
“Such operator which subtracts right operand from the left and then assigns the
value to left operand.”
a -= b OR a=a–b
“Such operator which multiplies two operands and assigns the value to left
operand.”
a *= b OR a=a*b
“Such operator which divides the left operand by the right operand and then
assigns the value to the left operand.”
a /= b OR a=a/b
\a
“An escape sequence that is used to give beep with the string of output stream
(cout<<"string") is represented by \a.”
#include<iostream>
using namespace std;
int main()
{ int a, b; OUTPUT:
cout<<"\aEnter first value:"; *Gives beep*
cin>>a; Enter first value: _
cout<<"\n\aEnter second value:"; *Gives another beep*
cin>>b;
Enter second value: _
return 0;
}
\n
“An escape sequence that is used to give new line to the string in output stream
(cout<<"string") is represented by \n.”
#include<iostream>
using namespace std;
int main() OUTPUT:
{ cout<<"Pakistan\nZindabad"; Pakistan
return 0; Zindabad
}
\t
“An escape sequence that is used to put a couple of whitespaces that makes
proceeding statements aligned in the string of output stream (cout<<"string")
is represented by \t.”
#include<iostream>
using namespace std;
int main() OUTPUT:
{ cout<<"Pakistan\tZindabad"; Pakistan Zindabad
return 0;
}
\r
“An escape sequence that is used to return back to the start of the string in the
output stream (cout<<"string") is represented by \r.”
#include<iostream>
using namespace std;
int main() OUTPUT:
{ cout<<"Pakistan\rZindabad"; Zindabad
return 0;
}
\b
“An escape sequence that is used to move the cursor one position back,
effectively deleting the previous character in the string of output stream
(cout<<"string") is represented by \”.”
#include<iostream>
using namespace std;
int main() OUTPUT:
{ cout<<"Hello\b World"; Hell World
return 0;
} *The ‘o’ is removed*
\\
“An escape sequence that is used to insert a backslash character in the string of
output stream (cout<<"string") is represented by \\.”
#include<iostream>
using namespace std;
int main() OUTPUT:
{ cout<<"This is a backslash: \\"; This is a backslash:\
return 0;
}
\”
“An escape sequence that is used to insert a double-quote in the string of output
stream (cout<<"string") is represented by \”.”
#include<iostream>
using namespace std;
int main() OUTPUT:
{ cout<<"He said, \"Hello World!\""; He said, “Hello World!”
return 0;
}
\’
“An escape sequence that is used to insert a single-quote in the string of output
stream (cout<<"string") is represented by \”.”
#include<iostream>
using namespace std;
int main() OUTPUT:
{ cout<<"It\’s a sunny day."; It’s a sunny day.
return 0;
}
FLOWCHART
“A graphical representation of step-by-step instructions in a sequence to describe a
computer program using shapes and objects is called flowchart.”
6. Start/Stop (Oval)
7. Flow Path (Arrows)
8. Input/Output (Parallelogram)
9. Process (Rectangle)
10. Decision/Condition (Diamond)
1. Decision Statement
2. Loop Statement
3. Jump Statement
1. “if” statement
2. “if-else” statement
3. “switch” statement
“if” statement
{
statement(s);
}
“if-else” statement
{
statement(s);
}
else
{
statement(s);
}
“Such if statement which occurs inside the block of code of if statement so that
to run two or more conditional expressions.”
Syntax:
if (condition 1) //Pseudo-code
{
if (condition 2)
{
statement(s);
}
}
“Such if-else statement which occurs inside the block of code of else statement
so that to run two or more conditional expressions of if program structure.”
“switch” statement
Flowchart of Switch:
“Such control statement that are executed for a specific number of times until a
certain condition is achieved is called loop or iteration statement.”
ITERATION
“Iteration (Loop) is a repetitive process that is performed again and again until
the condition is met.”
1. “for” loop
2. “while” loop
3. “do-while” loop
“for” loop
“An iteration or loop statement that allows to write a loop expression that is
executed a specific number of times where it terminates when the condition
becomes false.”
“while” loop
Example: Two Different programs using for and while loop, with same output.
A while loop can handle complex conditions or situations where the number of iterations is
unknown beforehand. For example, reading data until a specific event occurs (e.g., reading a
file until End of File: EOF is reached) is more straightforward with a while loop. A for loop is
generally better for fixed, countable iterations but can be less intuitive for such cases.
Here is an example that shows how the while loop is more flexible when the number of
iterations is not known beforehand.
“do-while” loop
“Such iteration or loop statement which always execute the code block once,
before checking if the condition is true, then it repeats the loop as long as the
condition is true.”
Syntax:
do {
// code block to be executed
}
while (condition);
It is used to terminate or continue the loop inside a program or stop the execution of a function.
In C++, there are five jump statements:
1. break
2. continue
3. goto
4. return
5. exit()
break statement
“Such jump statement which is used to exit from a loop or switch statement is
known as break statement.”
Syntax: break;
continue statement
“Such jump statement which is used to skip the current iteration of a loop and
proceed with the next iteration is known as continue statement.”
Syntax: continue;
goto statement
Syntax:
if (condition) {
goto label;
}
label: statement;
return statement
“The return statement is used to exit from a function and optionally return a
value.”
Syntax:
return value/variable/expression;
exit() statement
Syntax:
#include <cstdlib>
void exit(int exit_code);
In C++, the default statement is used in a switch statement to provide a fallback action when
none of the cases match the given value. If the switch expression doesn’t match any of the
specified cases, the default block will be executed.
In this example, if day is not ranging between 1 – 7, the default block will run, and it will print
"Invalid Day Number".
In C++, we use curly braces { } to create a block of statements. This is important because it
groups multiple statements together so that they can be treated as a single unit.
Without braces, only the first statement after if, else, while, or other control structures
would be executed.
5 FUNCTIONS IN C++
“A key part of programming that is a block of reusable and organized code,
usually perform a single, related action.”
1. Pre-defined functions
2. User-defined functions
1. Function declaration
2. Function definition
3. Function calling
A function declaration, also known as a function prototype, informs the compiler about the
function name, its return type, and the parameters it expects.
This is necessary when the function definition is provided after the function call or when the
function is defined in a different file.
Syntax:
return_type function_name(parameter_list);
Example:
1. Function Name
“A unique identifier similar to variable name, given to the function so it can be
called by this name from other parts of the program.”
2. Return Type
“The data type of the value that the function will return to the caller.”
It can be any valid data type in C++, such as int, double, char, void.
3. Parameters
“The variables with data types that represent the data that a function expects to
receive when it is called.”
Parameters allow you to pass values into a function so that the function can perform its task
using those values.
It includes the function body, where the logic of the function is written.
Syntax:
return_type function_name(parameters) {
// Body of the function with statements
}
Example:
When a function is called, the control of the program shifts to the function’s body, executes the
code inside it, and then returns control back to where the function was called.
Syntax:
function_name(arguments);
Arguments
“Arguments are the actual values or expressions passed to the function when it
is called.”
Types of Arguments:
A local variable cannot be reused in a function even when it is used in the main function.
Syntax:
return_type function_name(parameters)
{
// Local variable:
data_type variable_name = value;
// other code instructions
}
Global variable is also known as external variable. It holds the value of variable during the entire
execution of a program.
Syntax:
// Global variable:
data_type variable_name = value;
return_type function_name(parameters)
{
// other code instructions
}
When we compile the code, the header file allows the main function to know about what is inside
the function declared in header file. The main function is the actual code in .cpp extension.
When using header file of any predefined function, <iostream> is written with #include.
#include<iostream>
2. Only the function declaration is provided in header file and the function definition is
provided in the source file.
3. When the programmer compiles these files, the add.h header file allows main.cpp to
know about the add function.