Module-2.
Control Structure and Functions
Control structures in C++ manage the flow of execution within a program. They enable
decision-making, repetition, and alteration of the sequential execution of code. These
structures are essential for creating programs that can handle various situations and
perform complex tasks.
Types of Control Structures
Sequential:
The default execution order, where statements are executed one after another in the
order they appear in the code.
Selection (Decision Making):
Allows the program to choose between different paths of execution based on a
condition.
if statement: Executes a block of code if a condition is true.
if-else statement: Executes one block of code if a condition is true and another block if it's
false.
else-if ladder: Chain multiple if conditions to check for different scenarios.
switch statement: Selects one of several code blocks to execute based on the value of a
variable.
Iteration (Looping):
Repeats a block of code multiple times.
for loop: Repeats a block of code a specific number of times.
while loop: Repeats a block of code as long as a condition is true.
do-while loop: Repeats a block of code at least once, and then continues to repeat as long
as a condition is true.
Jump:
Transfers control to another part of the program.
break statement: Terminates the nearest enclosing loop (for, while, do-while)
or switch statement.
continue statement: Skips the rest of the current iteration of a loop and proceeds to the
next iteration.
goto statement: Jumps to a labeled statement within the same function (generally
discouraged due to potential for unstructured code).
return statement: Exits the current function and returns a value (if any) to the caller.
1
exit() function: Terminates the entire program.
Decision Making Statement
Decision-making statements in C++ control the flow of execution based on
conditions. These statements allow a program to choose different paths of execution
depending on whether a condition is true or false. The primary decision-making
statements in C++ are:
if statement: Executes a block of code only if a specified condition is true.
C++
if (condition) {
// Code to execute if the condition is true
}
if-else statement: Executes one block of code if the condition is true and another block
if the condition is false.
C++
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
nested if statement: An if statement inside another if statement, useful for handling
multiple conditions.
C++
if (condition1) {
// Code to execute if condition1 is true
if (condition2) {
// Code to execute if both condition1 and condition2 are true
}
}
if-else-if ladder: A sequence of if-else statements, useful for checking multiple
conditions in order.
C++
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else if (conditionN) {
// Code to execute if conditionN is true
2
} else {
// Code to execute if none of the conditions are true
}
switch statement: Selects one of several code blocks to execute based on the value of
a variable.
C++
switch (variable) {
case value1:
// Code to execute if variable equals value1
break;
case value2:
// Code to execute if variable equals value2
break;
default:
// Code to execute if variable doesn't match any case
}
Jump Statements:
o break: Terminates the loop or switch statement and transfers execution to the
statement immediately following the loop or switch.
o continue: Skips the rest of the current iteration of a loop and proceeds to the next
iteration.
o goto: Transfers control to a labeled statement within the same function. (Generally
discouraged due to potential for creating spaghetti code).
o return: Terminates the execution of a function and returns control (and a value, if any)
to the calling function.
Control statements in C++ manage the flow of execution within a program. They enable
decisions, repetitions, and jumps, altering the sequential execution of code. These
statements are crucial for creating dynamic and responsive programs.
Types of Control Statements
Selection Statements:
o if statement: Executes a block of code if a condition is true.
C++
int age = 20;
if (age >= 18) {
3
std::cout << "Adult" << std::endl;
}
if-else statement: Executes one block of code if a condition is true and another block if
it is false.
int num = 7;
if (num % 2 == 0) {
std::cout << "Even" << std::endl;
} else {
std::cout << "Odd" << std::endl;
}
if-else if-else ladder: Checks multiple conditions sequentially and executes the
corresponding block of code.
int score = 75;
if (score >= 90) {
std::cout << "A" << std::endl;
} else if (score >= 80) {
std::cout << "B" << std::endl;
} else if (score >= 70) {
std::cout << "C" << std::endl;
} else {
std::cout << "D" << std::endl;
}
switch statement: Selects one of many code blocks to execute based on the value of a
variable.
int day = 3;
switch (day) {
case 1:
std::cout << "Monday" << std::endl;
break;
case 2:
std::cout << "Tuesday" << std::endl;
break;
case 3:
std::cout << "Wednesday" << std::endl;
break;
default:
std::cout << "Invalid day" << std::endl;
}
4
Iteration Statements (Loops):
o for loop: Repeats a block of code a specified number of times.
for (int i = 0; i < 5; i++) {
std::cout << i << " ";
}
// Output: 0 1 2 3 4
while loop: Repeats a block of code as long as a condition is true.
int i = 0;
while (i < 5) {
std::cout << i << " ";
i++;
}
// Output: 0 1 2 3 4
do-while loop: Repeats a block of code at least once and then continues as long as a
condition is true.
int i = 0;
do {
std::cout << i << " ";
i++;
} while (i < 5);
// Output: 0 1 2 3 4
Jump Statements:
o break statement: Terminates the nearest enclosing loop or switch statement.
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
std::cout << i << " ";
}
// Output: 0 1 2 3 4
continue statement: Skips the rest of the current iteration of a loop and proceeds to
the next iteration.
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue;
}
std::cout << i << " ";
5
}
// Output: 1 3 5 7 9
goto statement: Transfers control to a labeled statement within the same function. It's
generally discouraged due to potential for creating complex and hard-to-maintain code.
int i = 0;
loop:
std::cout << i << " ";
i++;
if (i < 5) {
goto loop;
}
// Output: 0 1 2 3 4
A function in C++ consists of several parts:
Return Type:
Specifies the data type of the value that the function returns. If the function does not
return any value, the return type is void.
Function Name:
The unique identifier used to call the function.
Parameter List:
A list of input values (arguments) that the function receives, enclosed in parentheses. It
can be empty if the function doesn't require any input. Each parameter has a data type
and a name.
Function Body:
The block of code enclosed in curly braces {} that contains the instructions to be
executed when the function is called.
Here's an example illustrating these parts:
C++
#include <iostream>
// Function declaration (prototype)
int add(int a, int b);
// Main function
int main() {
int num1 = 10;
6
int num2 = 20;
int sum;
// Function call
sum = add(num1, num2);
std::cout << "The sum is: " << sum << std::endl;
return 0;
}
// Function definition
int add(int a, int b) {
int result = a + b;
return result;
}
In this example:
int is the return type of the add function.
add is the function name.
(int a, int b) is the parameter list, indicating that the function accepts two integer
arguments.
{ int result = a + b; return result; } is the function body, where the addition is performed
and the result is returned.
The main function calls the add function with num1 and num2 as arguments, and the
returned value is stored in the sum variable.
Parts of Functions
A function in C++ consists of several parts:
Return Type:
Specifies the data type of the value that the function returns. If the function does not
return any value, the return type is void.
Function Name:
The unique identifier used to call the function.
Parameter List:
A list of input values (arguments) that the function receives, enclosed in parentheses. It
can be empty if the function doesn't require any input. Each parameter has a data type
and a name.
7
Function Body:
The block of code enclosed in curly braces {} that contains the instructions to be
executed when the function is called.
Here's an example illustrating these parts:
#include <iostream>
// Function declaration (prototype)
int add(int a, int b);
// Main function
int main() {
int num1 = 10;
int num2 = 20;
int sum;
// Function call
sum = add(num1, num2);
std::cout << "The sum is: " << sum << std::endl;
return 0;
}
// Function definition
int add(int a, int b) {
int result = a + b;
return result;
}
In this example:
int is the return type of the add function.
add is the function name.
(int a, int b) is the parameter list, indicating that the function accepts two integer
arguments.
{
int result = a + b; return result; } is the function body, where the addition is performed
and the result is returned.
The main function calls the add function with num1 and num2 as arguments, and the
returned value is stored in the sum variable.
8
C++ User-defined Function Types
For better understanding of arguments and return values in functions, user-defined
functions can be in various forms like:
Function with no argument and no return value
Function with no argument but return value
Function with argument but no return value
Function with argument and return value
No Arguments Passed and No Return Value
#include <iostream>
using namespace std;
// declare a function
// with no arguments and no return value
void say_hello();
int main() {
// no argument is passed to the function
say_hello();
return 0;
}
void say_hello() {
cout << "Hello!";
}
No Arguments Passed but a Return Value
#include <iostream>
using namespace std;
// declare a function with no arguments
// and return type string
string get_username();
int main() {
// call prime and assign return value to is_prime
string user_name = get_username();
9
cout << "Hello, " << user_name;
}
string get_username() {
string name;
cout << "Enter your user name\n";
cin >> name;
return name;
}
Arguments Passed but no Return Value
#include <iostream>
using namespace std;
void say_hello(string name);
int main() {
cout << "Enter your name: ";
string name;
cin >> name;
// pass argument num function prime()
say_hello(name);
void say_hello(string name) {
cout << "Hello " << name ;
}
Arguments Passed and a Return Value
#include <iostream>
using namespace std;
// declare a function
// with int argument and int return type
10
bool check_prime(int n);
int main() {
int num;
cout << "Enter a positive integer to check: ";
cin >> num;
int is_prime = check_prime(num);
if (is_prime == true)
cout << num << " is a prime number.";
else
cout << num << " is not a prime number.";
return 0;
}
// function to check if the number is prime
bool check_prime(int n) {
// 0 and 1 are not prime numbers
if (n == 0 || n == 1) {
return false;
}
for (int i = 2; i <= n/2; ++i) {
if (n % i == 0)
return false;
}
return true;
}
11
Void Function
A void function in C++ is a function that does not return a value. It performs a task and
then exits without sending any data back to the caller. The void keyword is used in the
function declaration and definition to specify that the function does not have a return
type.
Here's an example:
C++
#include <iostream>
// Function declaration
void greet(std::string name);
int main() {
std::string my_name = "World";
greet(my_name); // Calling the function
return 0;
}
// Function definition
void greet(std::string name) {
std::cout << "Hello, " << name << "!" << std::endl;
}
In this example, the greet function takes a string name as input and prints a greeting
message. It does not return any value, so its return type is void. The main function calls
the greet function, and the code within greet is executed. After greet finishes, control
returns to main, and the program continues.
Value Parameters
In C++, a value parameter, also known as pass-by-value, is a method of passing
arguments to a function where a copy of the actual argument's value is passed to the
function's formal parameter. Any modifications made to the parameter inside the function
do not affect the original argument outside the function.
Here's an example:
#include <iostream>
void modifyValue(int x) {
std::cout << "Inside function, before modification: x = " << x << std::endl;
x = x * 2;
std::cout << "Inside function, after modification: x = " << x << std::endl;
12
}
int main() {
int num = 10;
std::cout << "Before function call: num = " << num << std::endl;
modifyValue(num);
std::cout << "After function call: num = " << num << std::endl;
return 0;
}
Output:
Before function call: num = 10
Inside function, before modification: x = 10
Inside function, after modification: x = 20
After function call: num = 10
Function Overloading
Function overloading in C++ allows multiple functions with the same name to be defined
within the same scope, as long as their parameter lists are different. This difference can
be in the number of parameters, the data types of parameters, or both. The compiler
determines which function to call based on the arguments provided in the function call.
Here's an example:
C++
#include <iostream>
// Function with two integer parameters
int add(int a, int b) {
return a + b;
}
// Function with three integer parameters
int add(int a, int b, int c) {
return a + b + c;
}
// Function with two double parameters
double add(double a, double b) {
return a + b;
}
13
int main() {
std::cout << "Sum of 2 and 3: " << add(2, 3) << std::endl; // Calls add(int, int)
std::cout << "Sum of 2, 3 and 4: " << add(2, 3, 4) << std::endl; // Calls add(int, int,
int)
std::cout << "Sum of 2.5 and 3.5: " << add(2.5, 3.5) << std::endl; // Calls add(double,
double)
return 0;
}
In this example, there are three functions named add, each taking different
parameters. When add is called, the compiler selects the appropriate function based on
the number and types of arguments passed. This allows for more readable and
maintainable code by using the same function name for operations that are conceptually
similar but operate on different data.
Virtual Function
A virtual function in C++ is a member function declared within a base class and redefined
in a derived class. When called through a base class pointer or reference, it dynamically
determines which version of the function to execute at runtime based on the actual object
type. This mechanism is crucial for achieving polymorphism.
Here's an example:
C++
#include <iostream>
using namespace std;
class Animal {
public:
virtual void makeSound() {
cout << "Generic animal sound" << endl;
}
};
class Dog : public Animal {
public:
void makeSound() override {
cout << "Woof!" << endl;
}
};
14
class Cat : public Animal {
public:
void makeSound() override {
cout << "Meow!" << endl;
}
};
int main() {
Animal* animal1 = new Animal();
Animal* animal2 = new Dog();
Animal* animal3 = new Cat();
animal1->makeSound(); // Output: Generic animal sound
animal2->makeSound(); // Output: Woof!
animal3->makeSound(); // Output: Meow!
delete animal1;
delete animal2;
delete animal3;
return 0;
}
In this example, makeSound is declared as a virtual function in
the Animal class. The Dog and Cat classes override this function with their specific
implementations. When makeSound is called through a base class pointer, the correct
version for the actual object type is executed, demonstrating polymorphism.
15