3.Programming in C++
3.Programming in C++
3 Operators:
1.Arithmetic Operators:
+ (Addition),- (Subtraction),* (Multiplication),/ (Division), % (Modulo): Returns the
remainder after division.
Operations of addition, subtraction, multiplication and division should not suppose an
understanding challenge for you since they literally correspond with their respective
mathematical operators.
The only one that may not be known by you is the module, specified with the
percentage sign (%). Module is the operation that gives the remainder of a division of
two integer values.
For example, if we write a = 11 % 3;
the variable a will contain 2 as the result
since 2 is the remainder from dividing 11 between 3.
2. Relational Operators:
== (Equal to): Checks if two operands are equal.
!= (Not equal to): Checks if two operands are not equal.
> (Greater than): Checks if the left operand is greater than the right operand.
< (Less than): Checks if the left operand is less than the right operand.
>= (Greater than or equal to): Checks if the left operand is greater than or equal to the right
operand.
<= (Less than or equal to): Checks if the left operand is less than or equal to the right
operand. Logical Operators: && (Logical AND): Returns true if both operands are true.
|| (Logical OR): Returns true if at least one operand is true.
Other Operators:
Size of: Returns the size of a data type or variable in bytes. ,
(Comma): Separates expressions, evaluates from left to right.
2.delete Operator: delete Operator: Deallocates memory that was previously allocated
dynamically using new. It releases the memory occupied by a single variable or an array.
Syntax: delete pointerName; // Deallocates memory for a single variable
delete[] arrayName; // Deallocates memory for an array
2.4 Manipulators:
In C++, manipulators are special functions or objects that modify the behavior of input/output
streams. They're used with stream objects (like cin and cout) to format input and output in a
specific
way. These manipulators are part of the <iomanip> header.Here are some commonly used
manipulators:
1. Setw setw(int n): Sets the width of the next output field to n spaces. #include <iostream>
#include <iomanip> int main() { int num = 123; std::cout << std::setw(10) << num <<
std::endl; // Outputs: " 123" return 0; }
2. setprecision setprecision(int n): Sets the decimal precision for floating-point numbers to n
digits.
#include <iostream> #include <iomanip>
int main() { double pi = 3.1415926535; std::cout << std::setprecision(4) << pi << std::endl;
// Outputs: "3.142" return 0; }
3. fixed and scientific fixed and scientific manipulators: Control the format of floating-point
numbers.
#include <iostream> #include <iomanip> int main() { double num = 123456.789; std::cout
<< std::fixed << num << std::endl; // Outputs: "123456.789000" std::cout << std::scientific
<< num << std::endl; // Outputs: "1.234568e+05" return 0; }
4. boolalpha boolalpha: Outputs boolean values as "true" or "false".
#include <iostream> #include <iomanip> int main() { bool value = true; std::cout <<
std::boolalpha << value << std::endl; // Outputs: "true" return 0; }
5. showpoint showpoint: Always shows the decimal point and trailing zeros for floating-
point numbers.
# include <iostream>
#include <iomanip> int main() { double num = 123.4; std::cout << std::showpoint << num
<< std::endl; // Outputs: "123.400" return 0; }
These manipulators offer flexibility in formatting output to suit specific requirements, making
the presentation of data more readable and user-friendly. Manipulators can be combined and
used together to achieve different formatting effects within C++ streams.
datum of a given type to another. There are several ways to do this in C++, the most
popular one, compatible with the C language is to precede the expression to be
converted by the new type enclosed between parenthesis ():
int i;
float f = 3.14;
i = (int) f;
The previous code converts the float number 3.14to an integer value (3). Here, the
typecasting operator was (int). Another way to do the same thing in C++ is using the
constructor form: preceding the expression to be converted by the type and enclosing
the
Expression between parenthesis:
i = int ( f );
Both ways of type casting are valid in C++. And additionally ANSI-C++ added new
typecasting operators more specific for object oriented programming
2.5 Functions:
In C++, functions are blocks of code that perform a specific task and can be called from
other parts of the program.
They're defined with a return type, a name, and can have parameters (inputs) and a body (the
code to execute).
Here's a simple example of a function in C++:
#include <iostream> // Function declaration or prototype
int add(int a, int b); // Function definition
int add(int a, int b)
{
return a + b;
}
int main()
{
int x = 5, y = 3;
int result = add(x, y); // Calling the add function
std::cout << "The sum is: " << result << std::endl;
return 0;
}
In this example: add is the name of the function. int before the function name indicates that
the function returns an integer.
Inside the parentheses are the parameters (int a, int b) that the function takes. These act as
placeholders for the values you'll pass when calling the function.
The function's body is enclosed in curly braces {} where the actual code to add two integers
is written.
The return statement specifies the value that the function will give back when called.
Types of functions
1.Built in functions :are part of compiler package. Part of standard library made available by
compiler. Can be used in any program by including respective header file.
2. User defined functions:Created by user or programmer. Created as per requirement of the
program.
Advantages
• Support for modular programming • Reduction in program size. • Code duplication is
avoided. • Code reusability is provided. • Functions can be called repetitively. • A set of
functions can be used to form libraries.
Function call
A function must be called by its name followed by argument list enclosed in semicolon.
Suppose int add(int,int); //prototype Now to this function add(x,y); //function call
or add(40,60);
Syntax: function_name (parameter list/argument);
add(x,y); add(40,60); add(void); or add(); Note: data type not to be mentioned.
Function definition
Syntax: function_type function_name(parameter list) { Local variable declaration;
Function body statement; Return statement; }
Function header
Function body
Function categories
i) Function with no return value and no argument. void add(void); ii) Function with
arguments passed and no return value. void add(int,int); iii) Function with no arguments but
returns a value. int add(void); iv) Function with arguments and returns a value. int
add(int,int);
void main() {
void disp(void); //prototype disp(); //caller function return 0; }
void disp() //calle function
{ cout<<“--------”<<endl;
}
ii. Function will not return any value but passes argument
#include<iostream.h>
#include<conio.h>
void add(int,int);
int main()
{
int a,b;
cout<<“enter values of a and b”<<endl;
cin>>a>>b;
add(a,b);
getch();
return 0;
}
void add(int x,int y)
{ int c;
c=x+y;
cout<<“addition is”<<c;
}
Return by Reference:
Returning by reference allows a function to return a reference to a variable.
It can be used to avoid copying large objects and to manipulate the original value.
Example: #include <iostream>
int& maxValue(int& a, int& b)
{
return (a > b) ? a : b;
}
int main()
{
int x = 5, y = 10;
int& max = maxValue(x, y); // Returning reference
max = 100; // Modifies the original value of x or y
std::cout << "Updated value: " << x << ", " << y << std::endl; // Output will show the
updated value
return 0;
}
Inline Function
These concepts are powerful tools in C++ that allow for more efficient memory usage and
enable functions to interact with variables in different ways, whether it's through declaration,
passing, or returning values.
Inline functions Inline functions in C++ are a way to hint to the compiler that it should insert
the entire body of the function wherever the function is called, rather than performing a
regular function call. This is used to reduce the function call overhead and improve
performance, especially for small functions.
To declare an inline function, you typically use the inline keyword before the function
definition: #include <iostream> // Inline function declaration inline int multiply(int a, int b) {
return a * b; }
int main()
{
int x = 5, y = 3;
int result = multiply(x, y); // Inline function call
std::cout << "The product is: " << result << std::endl;
return 0; }
When the compiler encounters an inline function call, it replaces the function call with the
actual function body at compile time. However, the compiler might ignore the inline keyword
suggestion if it deems it unnecessary, and ultimately, it's up to the compiler's discretion
whether to inline a function or not. Inline functions are handy for small functions, like
accessors or mutators in classes, as they eliminate the overhead of a function call, but they
might not be suitable for large or complex functions since inlining them could lead to larger
executable size. Remember, using inline is a suggestion to the compiler for optimization; the
compiler might choose not to inline a function in certain circumstances, like recursive
functions, functions with loops, or functions with too many conditional statements.
Default arguments
Default arguments in C++ allow you to provide default values for function parameters. When
a function is called without providing values for these parameters, the default values are used.
Here's an example:
#include <iostream> // Function with default arguments
void greet(std::string name = "Guest", int age = 0)
{ std::cout << "Hello, " << name << "! Age: " << age << std::endl; }
int main() { greet(); // Calling greet without arguments, default values used
greet("Alice"); // Providing only the name, age defaults to 0
greet("Bob", 30); // Providing both name and age return 0; }