BCA C++ Unit 1 B
BCA C++ Unit 1 B
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
Base Case:
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)
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.
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);
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
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 = #
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
*ptr = 20;
int main()
return 0;