Chapter - 3
Chapter - 3
<iostream> It is used to define the cout, cin and cerr objects, which correspond to standard output stream,
standard input stream and standard error stream, respectively.
<iomanip> It is used to declare services useful for performing formatted I/O, such as setprecision and setw.
#include <iostream>
using namespace std;
int main( ) {
cout <<"Welcome to C++ class";
}
Standard input stream (cin)
The cin is a predefined object of istream class.
It is connected with the standard input device, which is usually a keyboard. The cin is
used in conjunction with stream extraction operator (>>) to read the input from a
console.
Let's see the simple example of standard input stream (cin):
#include <iostream>
using namespace std;
int main( ) {
int age;
cout << "Enter your age: ";
cin >> age;
cout << "Your age is: " << age << endl;
}
cin can accept multiple input values to be stored in different variables
Example: cin >> num1 >> num2
Formatting Numbers for Program Output
Proper output formatting contributes to ease of use and user satisfaction
cout with stream manipulators can control output formatting
Manipulator Action
setw (n) Set the field width to n
scientific Set the output to display real numbers in scientific
notation
endl Output a newline character and display all characters
in the buffer
fixed Always show a decimal point and use a default of six
digits after the decimal point. Fill with trailing zeros,
if necessary.
setprecision(n) Set the floating-point precision to n places.
The field width manipulator must be included for each value in the data stream sent
to cout
Other manipulators remain in effect until they are changed
Formatting floating-point numbers requires three field-width manipulators to:
Set the total width of the display
Force a decimal place
Set the number of significant digits after the decimal point
Example:
cout << "|" << setw(10) << fixed << setprecision(3) << 25.67 << "|";
produces this output: | 25.670|4
Case Study:
Length Conversion: Write a program that takes as input given lengths expressed in feet
and inches. The program should then convert and output the lengths in centimeters.
Assume that the given lengths in feet and inches are integers.
Functions
A function is a group of statements that together perform a task. Every C++ program has
at least one function, which is main(), and all the most trivial programs can define
additional functions.
A function is known with various names like a method or a sub-routine or a procedure
etc.
When your program starts, main() is called automatically. main( ) might call other
functions, some of which might call still others.
A C++ function definition consists of a function header and a function body.
A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function.
The reason why we use functions is to aid modularization of a program and a function
reduces program size.
Any fragments of code that are needed frequently in a program are best candidates to be
written as a function.
Advantage of functions
Code Reusability
By creating functions in C++, you can call it many times. So we don't need to write the
same code again and again.
Code optimization
It makes the code optimized, we don't need to write much code.
Types of Functions
There are two types of functions in C++ programming:
1. Library Functions: are the functions which are declared in the C++ header files.
if you include the cmath header file: #include <cmath> you can access predifend
method under the cmath header file see it below
Using Mathematical Library Functions example
2. User-defined functions: are the functions which are created by the C++ programmer, so
that he/she can use it many times. It reduces complexity of a big program and optimizes the
code.
Function Declarations
As you can’t use variables before declarations (telling the compiler what the variable
is), you can’t use function before telling the compiler what this function is.
The common approach to declare functions is at the beginning of the program.
The function declaration (function prototype) tells the compiler that later on in the
program a function introduced in the declaration is going to be used.
Function declaration is terminated with semicolon. If the function has arguments, then
they should be indicated in the declaration.
A function declaration has the following parts
return_type function_name( parameter list );
Examples :- int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required, so
following is also valid declaration − int max(int, int);
Function Definition
A function definition consists of two parts: interface and body.
The interface of a function (called its prototype) specifies how it may be used.
It consists of three entities:
The function name. This is simply a unique identifier.
The function parameters (also called its signature)-: this is a set of zero or more
typed identifiers used for passing values to and from the function.
The function return type. This specifies the type of value the function returns. A
function which returns nothing should have the return type void.
The body of a function contains the computational steps (statements) that comprise
the function.
function definition example
int max(int num1, int num2)
{
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
The function body is placed in one place in memory. But it could be invoked in several
places in the program.
Calling Functions
Calling functions is invoking function to execute.
The function call involves the function name, followed by parentheses.
The function call is similar to its declaration except that the return type is not
mentioned.
The call is terminated by semicolon.
Executing the call statement causes the function to execute, i.e. control is
transferred to the function, the statements in the function definition are executed
and then control returns to the statement following the function call.
#include <iostream>
using namespace std;
int max(int num1, int num2); // function declaration
int main () {
int a = 100, b = 200, int ret;
ret = max(a, b); // calling a function to get max value.
cout << "Max value is : " << ret << endl;
return 0;
}
// function defination
int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result; }
Pass By Value and Pass By Reference
Pass By Value
In call by value method of parameter passing, the values of actual parameters are
copied to the function’s formal parameters.
There are two copies of parameters stored in different memory locations.
One is the original copy and the other is the function copy.
Any changes made inside functions are not reflected in the actual parameters of the
caller.
Advantages of Call by Value in C++
Functions are free to modify the passed values without affecting the original data.
Great while working with multithreaded or asynchronous programs where we
need to keep track of the values.
Pass by value method can be used to convert a string from an integer without
modifying its value.
Pass By Value and Pass By Reference
Disadvantages of Call by Value in C++
Since pass by value is implemented by passing a copy of the data, the data size
increases (doubles). This may not be an issue with smaller programs but can cost
efficiency in larger programs.
If the argument is too large, copying the values can take a significant amount of
time.
There is no way to propagate back the updated values through the parameters.