C++ INPUTS and OUTPUTS
C++ INPUTS and OUTPUTS
C++ INPUTS and OUTPUTS
C++ comes with libraries that provide us with many ways for performing input and output. In C++ input
and output are performed in the form of a sequence of bytes or more commonly known as streams.
• Input Stream: If the direction of flow of bytes is from the device (for example, Keyboard) to the
main memory then this process is called input.
• Output Stream: If the direction of flow of bytes is opposite, i.e., from main memory to device
(display screen) then this process is called output.
1. iostream: iostream stands for standard input-output stream. This header file contains
definitions to objects like cin, cout, cerr etc.
2. iomanip: iomanip stands for input output manipulators. The methods declared in this file are
used for manipulating streams. This file contains definitions of setw, setprecision, etc.
3. fstream: This header file mainly describes the file stream. This header file is used to handle the
data being read from a file as input or data being written into the file as output.
The two keywords cout in C++ and cin in C++ are used very often for printing outputs and taking inputs
respectively. These two are the most basic methods of taking input and printing output in C++. To use
cin and cout in C++ one must include the header file iostream in the program.
The standard output device is the display screen. The C++ cout statement is the instance of the ostream
class. It is used to produce output on the standard output device which is usually the display screen. The
data needed to be displayed on the screen is inserted in the standard output stream (cout) using the
insertion operator(<<)
In the above program the insertion operator(<<) inserts the value of the string variable sample followed
by the string “A computer science portal for geeks” in the standard output stream cout which is then
displayed on screen.
#include <iostream>
using namespace std;
int main()
{
char sample[] = "GeeksforGeeks";
cout << sample << " - A computer science portal for geeks";
return 0;
}
#include <iostream>
using namespace std;
int main() {
char str[] = "Hello C++";
cout << "Value of str is : " << str << endl;
return 0;
}
2. Standard input stream (cin):
Usually, the input device in a computer is the keyboard. C++ cin statement is the instance of the
class istream and is used to read input from the standard input device which is usually a keyboard.
The extraction operator(>>) is used along with the object cin for reading inputs. The extraction operator
extracts the data from the object cin which is entered using the keyboard.
#include <iostream>
using namespace std;
int main()
{
int age;
cout << "Enter your age:";
cin >> age;
cout << "\nYour age is: " << age;
return 0;
}
#include <iostream>
using namespace std;
int main() {
char name[50];
cout << "Please enter your name: ";
cin >> name;
cout << "Your name is: " << name << endl;
return 0;
}
The above program asks the user to input the age. The object cin is connected to the input device. The
age entered by the user is extracted from cin using the extraction operator (>>) and the extracted
data is then stored in the variable age present on the right side of the extraction operator .
The C++ cerr is the standard error stream which is used to output the errors. This is also an instance of
the ostream class. As cerr in C++ is un-buffered so it is used when one needs to display the error
message immediately. It does not have any buffer to store the error message and display later.
The main difference between cerr and cout comes when you would like to redirect output using “cout”
that gets redirected to file if you use “cerr” the error doesn’t get stored in file. (This is what un-buffered
means ..It cant store the message)
#include <iostream>
using namespace std;
int main()
{
cerr << "An error occured";
return 0;
}
#include <iostream>
using namespace std;
int main() {
char str[] = "Unable to read....";
cerr << "Error message : " << str << endl;
return 0;
}
This is also an instance of ostream class and used to display errors but unlike cerr the error is first
inserted into a buffer and is stored in the buffer until it is not fully filled. or the buffer is not explicitly
flushed (using flush()). The error message will be displayed on the screen too.
#include <iostream>
using namespace std;
int main()
{
clog << "An error occured";
return 0;
}
#include <iostream>
using namespace std;
int main() {
char str[] = "Unable to read....";
clog << "Error message : " << str << endl;
return 0;
}
1. for Loop
A for loop is a repetition control structure which allows us to write a loop that is executed a specific
number of times. The loop enables us to perform n number of steps together in one line.
In for loop, a loop variable is used to control the loop. First initialize this loop variable to some value,
then check whether this variable is less than or greater than counter value. If statement is true, then
loop body is executed and loop variable gets updated . Steps are repeated till exit condition comes.
• Initialization Expression: In this expression we have to initialize the loop counter to some value.
for example: int i=1;
• Test Expression: In this expression we have to test the condition. If the condition evaluates to
true then we will execute the body of loop and go to update expression otherwise we will exit
from the for loop. For example: i <= 10;
• Update Expression: After executing loop body this expression increments/decrements the loop
variable by some value. for example: i++;
Syntax:
for (initialization expr; test expr; update expr)
{
// body of the loop
// statements we want to execute
}
Flow Diagram:
int main() {
for (int i = 1; i <= 5; ++i) {
cout << i << " ";
}
return 0;
}
Output
1 2 3 4 5
2. While Loop
While studying for loop we have seen that the number of iterations is known beforehand, i.e. the
number of times the loop body is needed to be executed is known to us. while loops are used in
situations where we do not know the exact number of iterations of loop beforehand. The loop execution
is terminated on the basis of test condition.
Syntax:
initialization expression;
while (test_expression)
{
// statements
update_expression;
}
Flow Diagram:
3. do while loop
In do while loops also the loop execution is terminated on the basis of test condition. The main
difference between do while loop and while loop is in do while loop the condition is tested at the end of
loop body, i.e do while loop is exit controlled whereas the other two loops are entry controlled loops.
Note: In do while loop the loop body will execute at least once irrespective of test condition.
// C++ program to illustrate do-while loop
#include <iostream>
using namespace std;
int main()
{
int i = 2; // Initialization expression
do
{
// loop body
cout << "Hello World\n";
// update expression
i++;
} while (i < 1); // test expression
return 0;
}
An infinite loop (sometimes called an endless loop ) is a piece of coding that lacks a functional exit so
that it repeats indefinitely. An infinite loop occurs when a condition always evaluates to true. Usually,
this is an error.
1. Use for loop when number of iterations is known beforehand, i.e. the number of times the loop
body is needed to be executed is known.
2. Use while loops where exact number of iterations is not known but the loop termination
condition is known.
3. Use do while loop if the code needs to be executed at least once like in Menu driven programs
• if statement
• if.... else statement
• switch statement
1. if statement
It is used to decide whether a certain statement or block of statements will be executed or not i.e if a
certain condition is true then a block of statement is executed otherwise not.
If the expression is true, then 'statement-inside' will be executed, otherwise 'statement-inside' is
skipped and only 'statement-outside' will be executed.
Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}
if(condition)
statement1;
statement2;
// Here if the condition is true, if block
// will consider only statement1 to be inside
// its block.
Flowchart
// C++ program to illustrate If statement
#include<iostream>
using namespace std;
int main()
{
int i = 10;
if (i > 15)
{
cout<<"10 is less than 15";
}
cout<<"I am Not in if";
}
#include< iostream.h>
int main( )
{
int x,y;
x=15;
y=13;
if (x > y )
{
cout << "x is greater than y";
}
}
2. if.... else statement
The if statement alone tells us that if a condition is true it will execute a block of statements and if the
condition is false it won’t. But what if we want to do something else if the condition is false. Here comes
the C else statement. We can use the else statement with if statement to execute a block of code when
the condition is false.
If the 'expression' is true or returns true, then the 'statement-block1' will get executed, else 'statement-
block1' will be skipped and 'statement-block2' will be executed.
Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
examples
// C++ program to illustrate if-else statement
#include<iostream>
using namespace std;
int main()
{
int i = 20;
if (i < 15)
cout<<"i is smaller than 15";
else
cout<<"i is greater than 15";
return 0;
}
void main( )
{
int x,y;
x=15;
y=18;
if (x > y )
{
cout << "x is greater than y";
}
else
{
cout << "y is greater than x";
}
}
C++ 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
You can divide up your code into separate functions and logically the division usually is in such that each
function performs a specific task
In C++ 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 C++ standard library provides numerous built-in functions that your program can call.
E.g. function strcat() to concatenate two strings, function memcpy() to copy one memory location to
another location and many more functions. A function is known with various names like a method or a
sub-routine or a procedure
➢ Defining a Function
The general form of a C++ function definition is as follows
A C++ function definition consists of a function header and a function body. Here are all the parts of a
function
• Return Type − A function may return a value. The return_type is the data type of the value the
function returns. Some functions perform the desired operations without returning a value. In
this case, the return_type is the keyword void.
• Function Name − This is the actual name of the function. The function name and the parameter
list together constitute the function signature.
• Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to
the parameter. This value is referred to as actual parameter or argument. The parameter list
refers to the type, order, and number of the parameters of a function. Parameters are optional;
that is, a function may contain no parameters.
• Function Body − The function body contains a collection of statements that define what the
function does
Example
Following is the source code for a function called max(). This function takes two parameters num1 and
num2 and return the biggest of both −
return result;
}
➢ Function Declarations
A function declaration tells the compiler about a function name and how to call the function. The actual
body of the function can be defined separately.
For the above defined function max(), following is the function declaration –
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
When a program calls a function, program control is transferred to the called function. A called function
performs defined task and when it’s return statement is executed or when its function-ending closing
brace is reached, it returns program control back to the main program.
To call a function, you simply need to pass the required parameters along with function name, and if
function returns a value, then you can store returned value. For example
#include <iostream>
using namespace std;
// function declaration
int max(int num1, int num2);
int main () {
// local variable declaration:
int a = 100;
int b = 200;
int ret;
return 0;
}
return result;
}
➢ Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the arguments.
These variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are created upon entry
into the function and destroyed upon exit.
While calling a function, there are three ways that arguments can be passed to a function
• Call by Value This method copies the actual value of an argument into the formal parameter of
the function. In this case, changes made to the parameter inside the function have no effect on
the argument
• Call by Pointer This method copies the address of an argument into the formal parameter.
Inside the function, the address is used to access the actual argument used in the call. This
means that changes made to the parameter affect the argument.
• Call by Reference This method copies the reference of an argument into the formal parameter.
Inside the function, the reference is used to access the actual argument used in the call. This
means that changes made to the parameter affect the argument.