0% found this document useful (0 votes)
14 views

BCA C++ Unit 1 B

Functions allow code to be reused by defining blocks of code that can be called from different parts of a program. There are two types of functions - standard library functions that are predefined and user-defined functions created by the programmer. Functions are declared with a return type, name, and parameters. Parameters allow data to be passed into functions. Functions can be called by name and return values or no return. Functions improve code organization and modularity.

Uploaded by

SK Bhatthi
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)
14 views

BCA C++ Unit 1 B

Functions allow code to be reused by defining blocks of code that can be called from different parts of a program. There are two types of functions - standard library functions that are predefined and user-defined functions created by the programmer. Functions are declared with a return type, name, and parameters. Parameters allow data to be passed into functions. Functions can be called by name and return values or no return. Functions improve code organization and modularity.

Uploaded by

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

Functions

 Function is a block of code that performs a specific task


 Function is a set of statements that takes input, does some specific computation, and
produces output
 For commonly or repeatedly tasks , function is defined .
 Instead of writing the same code again and again for different inputs, function can be
called

Two types of function:


 Standard Library Functions: Predefined in C++
 User-defined Function: Created by users
User-defined Function
 C++ allows the programmer to define their own function.
 When the function is invoked from any part of the program, it all executes the codes defined in the
body of the function

Function Declaration
returnType functionName (parameter1, parameter2,...)
{
// function body
}
int max(int x, int y)

if (x > y)

return x;

else

return y;

}
Calling a Function
int main( )
{
int a = 10, b = 20;
int m ;
m= max(a, b); // Calling a function
cout << "m is " << m;
return 0;
}
#include <iostream>
using namespace std;
void display( )
{
cout << " Hello BCA students";
}
int main( ) Output :
{ int i; Hello BCA students
for( i=0 ; i<5; i++) Hello BCA students
{ Hello BCA students
display( ); Hello BCA students
} Hello BCA students
return 0;
}
Need of Functions
 Functions help us in reducing code redundancy .
 Instead of writing the same code, again and again, we create a function and call it
everywhere
 Functions make code modular
 Functions provide abstraction. For example, we can use library functions without worrying
about their internal work
Function Parameters
 Actual Parameters // arguments passed at the time of calling a function
 Formal Parameters // arguments mentioned at the time of definition / declaration of function
#include <iostream>
using namespace std;
void fun(int x) // definition of function -----x is formal parameter
{
cout<<x ;
}
int main( )
{
int x = 20;
fun(x); // calling of function -------- x is actual parameter
return 0;
}
Parameter Passing
 Call by value
 Call by reference
Call by value
 Call by value is used where the value of x is not modified using the function fun( )
using namespace std;
void fun(int x)
{
x = 30;
}
int main()
{
int x = 20;
fun(x);
cout << "x = " << x;
return 0;
}
Output :
x= 20
Call by Value
#include <iostream>
using namespace std;
void fun(int* ptr)
{
*ptr = 30;
}
int main()
{
int x = 20;
fun(&x);
cout << "x = " << x;
return 0;
}
Output :
x= 30
 dereference operator * is used to access the value at an address
 address operator & is used to get the address of a variable of any data type
// program to add two numbers using a function
#include <iostream>
using namespace std;
int add(int a, int b)
{
return (a + b);
}
int main( )
{
int sum;
sum = add(100, 78);
cout << "100 + 78 = " << sum << endl;
return 0;
}
Function Prototype
void add(int, int); // function prototype
int main()
{
add(5, 3); // calling the function before declaration.
return 0;
}
void add(int a, int b) // function definition
{
cout << (a + b);
}
Types of Functions
1) Void Function with No Parameters
#include <iostream>
using namespace std;
void greet( )
{
cout << "Hello BCA 4th Sem" << endl;
}
int main( )
{
greet( );
return 0;
}
2) Void Function with Parameters
#include <iostream>
using namespace std;
void sum(int a, int b)
{
cout << "Sum: " << (a + b) << endl;
}
int main( )
{
sum(5, 3);
return 0;
}
3) Function with No Parameters and Return Value
#include <iostream>
using namespace std;
int sum( )
{
int x , y, z;
cin>>x>>y;
z=x+y;
return z;
}
int main( )
{
int a = sum( );
cout << "Sum: " << a<< endl;
return 0;
}
4) Function with Parameters and Return Value
#include <iostream>
using namespace std;
int add(int a, int b)
{
return a + b;
}
int main( )
{
cout << "Sum: " << add(5, 3) << endl;
return 0;
}
Recursion

 Recursion is a programming technique where a function calls itself directly or indirectly


in order to solve a problem.
 Recursion is achieved by defining a function that includes a call to itself within its own
definition.
Recursion depends on two components:

Base Case:

 This is the condition where the recursion stops.

 Without a base case, the function would continue calling itself indefinitely, leading to
a stack overflow error.

Recursive Case:

 This is the case where the function calls itself with modified arguments to progress
towards the base case.
//Example 1 for Recursion
#include <iostream>
using namespace std;
void countdown(int n)
{
if (n > 0)
{
cout << n << " ";
countdown(n - 1); // Recursively call countdown with n-1
}
}
int main()
{
cout << "Countdown: ";
countdown(5); // Start the countdown from 5
cout << endl;
return 0;
}
// Example for Recursive Factorial Program
#include <iostream>
using namespace std;
unsigned long long factorial(unsigned int n)
{
if (n == 0 || n == 1)
{
return 1; // Base case: factorial of 0 and 1 is 1
} else {
return n * factorial(n - 1); // Recursive case: factorial of n is n multiplied by factorial of (n-1)
}
}
int main()
{
unsigned int number;
cout << "Enter a non-negative integer: ";
cin >> number;
cout << "Factorial of " << number << " is: " << factorial(number) << endl;
return 0;
}
Namespace
 namespace is a declarative region that provides a scope for identifiers (such as variables,
functions, and classes)

 Used to avoid name collisions and organize code logically

 Namespaces help in preventing naming conflicts between different parts of a program,


especially when libraries, frameworks, or multiple developers are involved in the
development process
Namespace Declaration:
 Namespace can be declared using the namespace keyword followed by the namespace name
namespace MyNamespace
{
// Declarations go here
}
Namespace Definition
 Definitions of identifiers (variables, functions, classes, etc.) within a namespace are placed
inside the namespace's declaration
namespace MyNamespace
{
int variable; // Example variable
void function(); // Example function
class MyClass { }; // Example class
}
Accessing Namespaces
 Identifiers within a namespace can be accessed using the scope resolution operator ::
MyNamespace::variable = 10;
MyNamespace::function( );

Using Directives
 The using directive allows you to bring all the names from a namespace into the
current scope, making them accessible without using the scope resolution operator
using namespace MyNamespace;
// Example Program for Namespace
#include <iostream>
Using namespace std;
namespace bca
{
Int x=20;
void display( )
{
std::cout << "Hello BCAStudents " << std::endl;
}
}
namespace btech
{
Int x = 40;
void display( )
{
std::cout << "Hello B.Tech students" << std::endl;
}
}
int main()
{
bca::display( );
cout<< bca::x;
btech::display();
cout<<btech::x;
return 0;
}
Exception
 Exception is an unexpected or erroneous event that occurs during the execution of a
program, disrupting the normal flow of control
 Exceptions are used to handle runtime errors and other exceptional conditions in a
structured and controlled manner
 When an exception occurs, it can be thrown explicitly using the throw keyword and
can be caught and handled using try and catch blocks
 Exception handling allows for the separation of error-handling logic from the main
code flow, improving code reliability and maintainability.
int main() {
try {
int dividend , divisor ;
cin>>dividend>>divisor;
if (divisor == 0)
{
throw std::runtime_error("Divide by zero error");
}
int result = dividend / divisor;
std::cout << "Result: " << result << std::endl;
}
catch (const std::runtime_error & e)
{
std::cerr << "Exception caught: " << e.what( ) << std::endl;
}
return 0;
}
 std::runtime_error is a standard exception class defined in the <stdexcept>
header
 It is commonly used to represent errors that occur during runtime
 "Divide by zero error" is string serves as an error message that describes the
nature of the exception being thrown
 throw is the keyword used to explicitly throw an exception .When this statement
is executed, it causes the program to exit the current execution context (function
or block) and search for an appropriate catch block to handle the thrown
exception
 e typically refers to the exception object that has been caught.
 e.what( ) is invoking the what( ) member function on the exception object e to
retrieve the error message associated with that exception
 std::cerr is used for printing error messages and diagnostic information
Operators
Arithmetic Operators:
 Arithmetic operators perform basic arithmetic operations such as addition, subtraction,
multiplication, division, and modulus
 Example: + (addition), - (subtraction), * (multiplication), / (division), % (modulus)

Assignment Operators:
 Assignment operators are used to assign values to variables.
 Example:
= (simple assignment)
+= (addition assignment)
-= (subtraction assignment)
*= (multiplication assignment)
/= (division assignment)
%= (modulus assignment),
Relational Operators
 Relational operators are used to compare two values
 Example
== (equal to)
!= (not equal to)
< (less than)
> (greater than)
<= (less than or equal to)
>= (greater than or equal to)
Logical Operators
 Logical operators perform logical operations on boolean values.
 Example
&& (logical AND)
|| (logical OR)
! (logical NOT)
Bitwise Operators
 Bitwise operators perform bitwise operations on integer operands.
 Example
& (bitwise AND)
| (bitwise OR)
^ (bitwise XOR)
~ (bitwise NOT)
<< (left shift)
>> (right shift)
Increment and Decrement Operators
 Increment and decrement operators are used to increment or decrement the value of a
variable.
 Example
++ (increment)
-- (decrement)
Conditional Operator (Ternary Operator)
 The conditional operator ? : is a ternary operator that provides a way of expressing conditional
statements
 Example
condition ? value_if_true : value_if_false
// Example program of conditional Operator
#include<iostream>
using namespace std;
int main( )
{
int number;
cout<<"Enter an integer: ";
cin>>number;
(number % 2 == 0) ? cout<<number : cout<<number;
return 0;
}
Member Access Operators
 Member access operators are used to access members of objects and structures
 Example
. (dot operator for accessing members of an object)
-> (arrow operator for accessing members through a pointer)
Sizeof Operator
 The sizeof operator is used to determine the size of a data type or an object.
 Example
sizeof(int)
sizeof(variable)

Comma Operator
 The comma operator , is used to separate expressions and evaluate them sequentially
 Example expr1, expr2, expr3
Flow Control
 Flow control in C++ refers to the mechanisms and structures used to control the order in which
statements are executed within a program.
 It allows programmers to make decisions, repeat blocks of code, and alter the flow of
execution based on various conditions
 Flow control structures allow C++ programmers to write structured and organized code by
controlling the sequence of execution based on conditions and looping requirements.
 These structures enhance code readability, maintainability, and flexibility.

Control structures in C++


Conditional Statements:
 if: Executes a block of code if a specified condition is true.
 else: Executes a block of code if the if condition is false.
 else if: Allows checking for multiple conditions after the initial if statement.
 switch: Evaluates an expression and executes code blocks based on matching cases.
// Example program of Conditional Statements
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter an integer: ";
cin >> num;
if (num > 0) {
cout << "The number is positive." << endl;
} else if (num < 0) {
cout << "The number is negative." << endl;
} else {
cout << "The number is zero." << endl;
}
return 0;
}
// Example program of Switch statement
#include <iostream>
using namespace std;
int main() {
char grade;
cout << "Enter your grade (A, B, C, D, or F): ";
cin >> grade;
switch(grade) {
case 'A':
cout << "Excellent! You've got an A." << endl;
break;
case 'B':
cout << "Good job! You've got a B." << endl;
break;
case 'C':
cout << "Well done! You've got a C." << endl;
break;
case 'D':
cout << "You've got a D. Work harder!" << endl;
break;
case 'F':
cout << "You've failed. You need to improve." << endl;
break;
default:
cout << "Invalid grade entered." << endl;
}
return 0;
}
Looping Statements
while: Executes a block of code repeatedly as long as a specified condition is true.
do-while: Similar to while, but it guarantees that the block of code is executed at least once.
for: Executes a block of code repeatedly for a fixed number of times.

Jump Statements
break: Terminates the loop or switch statement and transfers control to the statement
immediately following the loop or switch.
continue: Skips the rest of the loop body and jumps to the next iteration of the loop.
return: Terminates the execution of a function and returns a value to the caller.
int count = 1;
while (count <= 5)
{
cout << count << " ";
count++;
}

do
{ cout << "Enter a positive number (enter 0 to exit): ";
cin >> number;
cout << "You entered: " << number << endl;
} while (number != 0);

for (int i = 1; i <= 5; i++)


{
cout << i << " ";
}
for (int i = 1; i <= 10; i++)
{
if (i == 6)
{
break; // Exit the loop when i is equal to 6
}
cout << i << " ";
}
for (int j = 1; j <= 10; j++)
{
if (j == 3)
{
continue; // Skip the current iteration when j is equal to 3
}
cout << j << " ";
}
Array
 Array is a data structure that stores a fixed-size sequential collection of elements of the
same type.
 Each element in the array is accessed by its index, which is an integer value indicating the
position of the element within the array
 Arrays provide a convenient way to store and access multiple values of the same data
type under a single name
Declaration of Array
 An array is declared by specifying the data type of its elements and the number of
elements it can hold
datatype arrayName[size];
int marks[50];
Initialization of Array
 Arrays can be initialized at the time of declaration or later using assignment statements
int marks[5] = {14, 2, 13, 8, 12};
Accessing Elements
 Elements of an array are accessed using their indices.
 Array indices start from 0 to (size - 1)
int x;
x = marks[2];
Iterating Over Arrays
 Loops like for or while are commonly used to iterate over array elements
for (int i = 0; i < 5; i++)
{
cout << marks[i] << " ";
}

Array Name
 Name of an array is a pointer to its first element.
//Example for Arrays
#include <iostream>
using namespace std;
void display(int arr[], int size)
{
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main()
{
int SIZE = 5;
int numbers[SIZE] = {10, 20, 30, 40, 50};
cout << "Array elements are :";
display(numbers, SIZE);

return 0;
}
Structures
 Structure is a user-defined data type
 It allows to group together variables of different data types under a single name
 Structures are used to represent a collection of related data items that may have different data
types
 Each variable within a structure is called a member or a field
Declaration of Structure
 Structures are declared using the struct keyword followed by the structure name.
 Syntax:
struct structName struct Person
{ {
string name;
member1Type member1Name; int age;
member2Type member2Name; double height;
/* ... */ };
};
Accessing Structure Members
 Structure members are accessed using the dot (.) operator
Person x;
x.name = "Alice";
x.age = 25;
x.height = 5.7;
Arrays of Structures
 Can create arrays of structures to store multiple instances of the same structure type
Person x[5];
x[0] = {"Amit", 35, 5.9};
x[1] = {"Rohit", 40, 6.1};
//WAP for Structures
#include <iostream>
using namespace std;
struct Point
{
int x;
int y;
};
void display(Point p)
{
cout << "Coordinates of the point: (" << p.x << ", " << p.y << ")" << endl;
}
int main()
{
Point p1 = {3, 5};
display(p1);
return 0;
}
Nested Structures:
 structures within structures
struct Address
{
string street;
string city;
string state;
string pincode;
};
struct Employee
{
string name;
int age;
Address address;
};
Accessing nested structure members:
– Employee x;
– x.name = "Mohit" ;
– x.age = 30;
– x.address.street = "42 Sector 2";
Pointers

 Pointers in C++ are variables that store memory addresses.


 Pointers "point" to the location of other variables or data structures in the
computer's memory

Declaring Pointers
int* ptr; // Declares a pointer to an integer
Assigning Pointers
 Pointers can be assigned the address of another variable using the address-of
operator (&)
int num = 5;
int* ptr = &num;
Dereferencing Pointers:
 Value at the memory address stored can be accessed using the dereference operator (*)
int value = *ptr; // value is now 5 (the value at the memory address pointed by ptr)

Using Pointers:
 Pointers are commonly used for dynamic memory allocation with new and delete
operators
– int * ptr = new int ; // Allocates memory for an integer
– *ptr = 10; // Assigns a value to the memory location
– delete ptr; // Deallocates the memory when done
Pointer Arithmetic:
 Can perform arithmetic operations on pointers, which allows to navigate through
memory
int x[ ] = {12, 28, 34, 42, 51};
int* ptr = x; // Points to the first element of the array
cout << *ptr << endl; // Output 12
ptr++; // Moves to the next element
cout << *ptr << endl; // Output 28
ptr++;
cout<<*ptr<<endl; // Output 34
Passing Pointers to Functions

 Pointers can be passed as arguments to functions, allowing functions to modify variables outside their scope

void modify(int* ptr)

*ptr = 20;

int main()

int num = 10;

modify(&num); // Passing the address of num

cout << num << endl; // Output: 20

return 0;

You might also like