C++ INPUTS and OUTPUTS

Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

INPUT / OUTPUT IN C++

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.

Header files available in C++ for Input/Output operations are:

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.

1. Standard output stream (cout):

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 .

3. The Standard Error Stream (cerr)

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;
}

4. The Standard Log Stream (clog):

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;
}

Loops in C and C++


Loops in programming come into use when we need to repeatedly execute a block of statements. For
example: Suppose we want to print “Hello World” 10 times.
In computer programming, a loop is a sequence of instructions that is repeated until a certain condition
is reached.
• An operation is done, such as getting an item of data and changing it, and then some condition
is checked such as whether a counter has reached a prescribed number.
• Counter not Reached: If the counter has not reached the desired number, the next instruction
in the sequence returns to the first instruction in the sequence and repeat it.
• Counter reached: If the condition has been reached, the next instruction “falls through” to the
next sequential instruction or branches outside the loop.

There are mainly two categories of loops:


1. Entry Controlled loops: In this type of loops the test condition is tested before entering the loop
body. For Loop and While Loop are entry-controlled loops.
2. Exit Controlled Loops: In this type of loops the test condition is tested or evaluated at the end of
loop body. Therefore, the loop body will execute atleast once, irrespective of whether the test
condition is true or false. do – while loop is exit controlled loop.

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:

// C++ program to illustrate for loop


#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 10; i++)
{
cout << "Hello World\n";
}
return 0;
}
#include <iostream>

using namespace std;

int main() {
for (int i = 1; i <= 5; ++i) {
cout << i << " ";
}
return 0;
}
Output

1 2 3 4 5

Here is how this program works

Iteration Variable i <= 5 Action

1st i=1 true 1 is printed. i is increased to 2 .

2nd i=2 true 2 is printed. i is increased to 3 .

3rd i=3 true 3 is printed. i is increased to 4 .

4th i=4 true 4 is printed. i is increased to 5 .

5th i=5 true 5 is printed. i is increased to 6 .

6th i=6 false The loop is terminated

// C++ Program to display a text 5 times


#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; ++i) {
cout << "Hello World! " << endl;
}
return 0;
}
Output
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!

Here is how this program works

Iteration Variable i <= 5 Action

1st i = 1 true Hello World! is printed and i is increased to 2 .

2nd i = 2 true Hello World! is printed and i is increased to 3 .

3rd i = 3 true Hello World! is printed and i is increased to 4 .

4th i = 4 true Hello World! is printed and i is increased to 5 .

5th i = 5 true Hello World! is printed and i is increased to 6 .

6th i = 6 false The loop is terminated

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:

// C++ program to illustrate while loop


#include <iostream>
using namespace std;
int main()
{
// initialization expression
int i = 1;
// test expression
while (i < 6)
{
cout << "Hello World\n";
// update expression
i++;
}
return 0;
}

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;
}

4. What about an Infinite Loop?

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.

// C program to demonstrate infinite loops


// using for and while
// Uncomment the sections to see the output
#include <stdio.h
int main ()
{
int i;
// This is an infinite for loop as the condition
// expression is blank
for ( ; ; )
{
printf("This loop will run forever.\n");
}
// This is an infinite for loop as the condition
// given in while loop will keep repeating infinitely
/*
while (i != 0)
{
i-- ;
printf( "This loop will run forever.\n");
}
*/
// This is an infinite for loop as the condition
// given in while loop is "true"
/*
while (true)
{
printf( "This loop will run forever.\n");
}
*/
}
Important Points:

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

Decision Making in C++


Decision making is about deciding the order of execution of statements based on certain conditions or
repeat a group of statements until certain specified conditions are met. C++ handles decision-making by
supporting the following statements,

• 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

return_type function_name( parameter list ) {


body of the function
}

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 −

// function returning the max between two numbers

int max(int num1, int num2) {


// local variable declaration
int result;

if (num1 > num2)


result = num1;
else
result = num2;

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.

A function declaration has the following parts

return_type function_name( parameter list );

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

int max(int, int);


Function declaration is required when you define a function in one source file and you call that
function in another file. In such case, you should declare the function at the top of the file calling
the function.
➢ Calling a Function
While creating a C++ function, you give a definition of what the function has to do. To use a function,
you will have to call or invoke that function.

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;

// calling a function to get max value.


ret = max(a, b);
cout << "Max value is : " << ret << endl;

return 0;
}

// function returning the max between two numbers


int max(int num1, int num2) {
// local variable declaration
int result;

if (num1 > num2)


result = num1;
else
result = num2;

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.

You might also like