FOP Unit-1 Part-2 (Introduction To Computer Programming)
FOP Unit-1 Part-2 (Introduction To Computer Programming)
Subject
Fundamentals of Programming (CE3002)
Unit – 1
Introduction of Computer Programming
(Part – 2)
CONTENTS
1. Program Structure
1.1. C++ Program Structure
1.2. Compile and Execute C++ Program
1.3. Java Program Structure
1.4. Compile and Execute Java Program
2. Tokens
2.1. Keywords
2.2. Identifiers
2.3. Constants
2.4. Strings
2.5. Special Symbols
2.6. Operators
3. Data Types
3.1. Primary or Built-in or Fundamental Data Types
3.2. Derived Data Types
3.3. Abstract or User-Defined Data Types
3.4. Data Types in Java
4. Variables
4.1. Variable Definition in C++
4.2. Variable Declaration in C++
4.3. Variable Scope in C++
4.4. Types of Variables in Java
5. Operators in C/C++/Java
5.1. Operators Precedence and Associativity
6. Constants/Literals
6.1. Defining Constants
7. Type Conversion/Type Casting
7.1. Type Conversion/Type Casting in C++
7.2. Type Conversion/Type Casting in Java
8. Escape Sequences
8.1. Escape Sequences in C/C++
8.2. Escape Sequences in Java
9. Input/Output
9.1. C++ Basic Input/Output
9.2. Java Basic Input/Output
9.3. Formatted I/O in C++
9.4. Formatted I/O in Java
1. Program Structure
When we consider a C++ or Java program, it can be defined as a collection of
objects that communicate via invoking each other's methods.
Let us now briefly look into what a class, object, methods, and instant variables
mean.
• Object − Objects have states and behaviors. Example: A dog has states -
colour, name, breed as well as behaviors - wagging, barking, eating. An object
is an instance of a class.
• Class − A class can be defined as a template/blueprint that describes the
behaviors/states that object of its type support.
• Methods − A method is basically a behavior. A class can contain many
methods. It is in methods where the logics are written, data is manipulated and
all the actions are executed.
• Instance Variables − Each object has its unique set of instance variables. An
object's state is created by the values assigned to these instance variables.
#include <iostream>
using namespace std;
• The C++ language defines several headers, which contain information that
is either necessary or useful to your program. For this program, the
header <iostream> is needed.
• The line using namespace std; tells the compiler to use the std namespace.
Namespaces are a relatively recent addition to C++.
• The next line '// main() is where program execution begins.' is a single-
line comment available in C++. Single-line comments begin with // and
stop at the end of the line.
• The line int main() is the main function where program execution begins.
• The next line cout << "Hello World"; causes the message "Hello World"
to be displayed on the screen.
• The next line return 0; terminates main( ) function and causes it to return the
value 0 to the calling process.
$ g++ hello.cpp
$ ./a.out
Hello World
Make sure that g++ is in your path and that you are running it in the directory
containing file hello.cpp.
About Java programs, it is very important to keep in mind the following points.
• Method Names − All method names should start with a Lower Case letter.
If several words are used to form the name of the method, then each inner
word's first letter should be in Upper Case.
• Program File Name − Name of the program file should exactly match the
class name.
When saving the file, you should save it using the class name (Remember
Java is case sensitive) and append '.java' to the end of the name (if the file
name and the class name do not match, your program will not compile).
But please make a note that in case you do not have a public class present
in the file then file name can be different than class name. It is also not
mandatory to have a public class in the file.
2. Tokens
A token is the smallest element of a program that is meaningful to the compiler.
Tokens can be classified as follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
2.1. Keywords
Keywords are reserved words with fixed meanings that cannot be changed.
The meaning and working of these keywords are already known to the compiler.
C++ has more numbers of keywords than C.
2.2. Identifiers
Identifier refers to the name of variables, arrays, functions, structures, classes,
and various other data structures. These are user defined names and consists of a
sequence of letters and digits. Both uppercase and lowercase letters can be used.
A special symbol underscore ( _ ) is also permitted.
There are certain rules to be followed by the user while naming identifiers,
otherwise, you would get a compilation error. These rules are:
2.3. Constants
Constants are referred to as fixed values that cannot change their value during
the execution of a program. They are also called literals. Constants may belong
to any of the data type.
• Types of Constants
o Integer constants – These constants store values of the int data type.
For instance: const int data = 5;
o Floating constants – These constants store values of the float data type.
For instance: const float e = 2.71;
o Character constants – A single char constants contains a single character
enclosed within pair of single quotes ‘ ’.
For instance: const char answer = ‘y’;
o String constants – These constants are also of the character data type but
differ in the declaration part. A string constant is a sequence of characters
enclosed in double quotes “ ”.
For instance: const char title[ ] = ‘‘CGPIT’’;
2.4. Strings
Just like characters, strings in C++ are used to store letters and digits. Strings
can be referred to as an array of characters as well as an individual data type.
It is enclosed within double quotes, unlike characters which are stored within
single quotes. The termination of a string in C++ is represented by the null
character, that is, ‘\0’. The size of a string is the number of individual characters
it has.
o char string[20] = {‘c’, ’g’, ‘p’, ‘i’, ‘t’, ‘\0’}; // reserves 20 bytes of memory
o char string[20] = “cgpit”; // reserves 20 bytes of memory
o char string [] = “cgpit”; //reserves the required amount of memory
• Brackets []: Opening and closing brackets are used as array element
reference. These indicate single and multidimensional subscripts.
• Parentheses (): These special symbols are used to indicate function calls and
function parameters.
• Braces {}: These opening and ending curly braces mark the start and end of
a block of code containing more than one executable statement.
• Comma (,): It is used to separate more than one statements like for separating
parameters in function calls.
• Colon (:): It is an operator that essentially invokes something called an
initialization list.
• Semicolon (;): It is known as a statement terminator. It indicates the end of
one logical entity. That’s why each individual statement must be ended with a
semicolon.
• Asterisk (*): It is used to create a pointer variable and for the multiplication
of variables.
• Assignment operator (=): It is used to assign values and for the logical
operation validation.
• Pre-processor (#): The pre-processor is a macro processor that is used
automatically by the compiler to transform your program before actual
compilation.
2.6. Operators
Operators are tools or symbols which are used to perform a specific operation
on data. Operations are performed on operands. Operators can be classified
into three broad categories according to the number of operands used.
• Unary: It involves the use of only a single operand. For Example increment and
decrement operators
• Binary: It involves the use of two operands. They are further classified as:
o Arithmetic
o Relational
o Logical
o Assignment
o Bitwise
o Conditional
• Ternary: It involves the use of three operands. Conditional Operator(?) is also
called ternary operator. For instance, ? : is used to in place of if-else conditions.
Syntax: (Expression1)? expression2: expression3;
3. Data Types
While writing program in any language, you need to use various variables to
store various information. Variables are nothing but reserved memory locations to
store values. This means that when you create a variable you reserve some space
in memory.
You may like to store information of various data types like character, wide
character, integer, floating point, double floating point, boolean etc. Based on the
data type of a variable, the operating system allocates memory and decides
what can be stored in the reserved memory.
Type Keyword
Boolean bool
Character char
Integer int
Several of the basic types can be modified using one or more of these type
modifiers −
• signed
• unsigned
• short
• long
The following table shows the variable type, how much memory it takes to
store the value in memory, and what is maximum and minimum value which can be
stored in such type of variables.
The size of variables might be different from those shown in the above table,
depending on the compiler and the computer you are using.
Following is the example, which will produce correct size of various data types
on your computer.
#include <iostream>
using namespace std;
int main() {
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
return 0;
}
This example uses endl, which inserts a new-line character after every line and
<< operator is being used to pass multiple values out to the screen. We are also
using sizeof() operator to get size of various data types.
When the above code is compiled and executed, it produces the following
result which can vary from machine to machine −
Size of char : 1
Size of int : 4
Size of short int : 2
Size of long int : 4
Size of float : 4
Size of double : 8
Size of wchar_t : 4
o Function
o Array
o Pointer
o Reference
o Class
o Structure
o Union
o Enumeration
o Typedef defined Datatype
• typedef Declarations
You can create a new name for an existing type using typedef. Following is
the simple syntax to define a new type using typedef −
For example, the following declaration tells the compiler that feet is another
name for int –
feet distance;
• Enumerated Types
Creating an enumeration requires the use of the keyword enum. The general
form of an enumeration type is −
Here, the enum-name is the enumeration's type name. The list of names is
comma separated.
For example, the following code defines an enumeration of colors called colors
and the variable c of type color. Finally, c is assigned the value "blue".
By default, the value of the first name is 0, the second name has the value 1,
and the third has the value 2, and so on. But you can give a name, a specific value
by adding an initializer. For example, in the following enumeration, green will
have the value 5.
Here, blue will have a value of 6 because each name will be one greater than
the one that precedes it.
There are eight primitive datatypes supported by Java. These are byte, short,
int, long, float, double, boolean, and char. Primitive datatypes are predefined by
the language and named by a keyword.
byte
o Default value is 0.
o Byte data type is used to save space in large arrays, mainly in place
of integers, since a byte is four times smaller than an integer.
o Example: byte a = 100, byte b = -50
short
int
long
float
double
boolean
char
Reference variables are created using defined constructors of the classes. They
are used to access objects. These variables are declared to be of a specific type
that cannot be changed. For example, Employee, Puppy, etc.
Class objects and various type of array variables come under reference
datatype.
A reference variable can be used to refer any object of the declared type or
any compatible type.
4. Variables
A variable provides us with named storage that our programs can manipulate.
Each variable in C/C++/Java has a specific type, which determines the size and
layout of the variable's memory; the range of values that can be stored within that
memory; and the set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and lowercase
letters are distinct because C/C++/Java is case-sensitive.
There are following basic types of variable in C++: bool, char, int, float, double,
void, wchar_t.
C++ also allows to define various other types of variables like Enumeration,
Pointer, Array, Reference, Data structures, and Classes.
type variable_list;
Here, type must be a valid C++ data type including char, w_char, int, float,
double, bool or any user-defined object, etc., and variable_list may consist of one
or more identifier names separated by commas. Some valid declarations are
shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; both declares and defines the variables i, j and k; which
instructs the compiler to create variables named i, j and k of type int.
For definition without an initializer: variables with static storage duration are
implicitly initialized with NULL (all bytes have the value 0); the initial value of all
other variables is undefined.
A variable declaration is useful when you are using multiple files and you
define your variable in one of the files which will be available at the time of
linking of the program. You will use extern keyword to declare a variable at any
place. Though you can declare a variable multiple times in your C++ program,
but it can be defined only once in a file, a function or a block of code.
Example -
Try the following example where variables have been declared at the top,
but it has been defined inside the main function −
#include <iostream>
using namespace std;
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
int main () {
// Variable definition:
int a, b;
int c;
float f;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c << endl ;
f = 70.0/3.0;
cout << f << endl ;
return 0;
}
When the above code is compiled and executed, it produces the following
result −
30
23.3333
int g = 20;
But the following is not a valid statement and would generate compile-time
error −
10 = 20;
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a, b;
int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}
• Global Variables
Global variables are defined outside of all the functions, usually on top of
the program. The global variables will hold their value throughout the life-time
of your program.
#include <iostream>
using namespace std;
// Global variable declaration:
int g;
int main () {
// Local variable declaration:
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
}
A program can have same name for local and global variables but value
of local variable inside a function will take preference.
For example –
#include <iostream>
using namespace std;
// Global variable declaration:
int g = 20;
int main () {
// Local variable declaration:
int g = 10;
cout << g;
return 0;
}
When the above code is compiled and executed, it produces the following
result −
10
• Instance Variables
A variable declared inside the class but outside the body of the method, is
called an instance variable. It is not declared as static.
• Classic/Static Variables
A variable that is declared as static is called a static variable. It cannot be
local. You can create a single copy of the static variable and share it among
all the instances of the class. Memory allocation for static variables happens
only once when the class is loaded in the memory.
5. Operators in C/C++/Java
An operator is a symbol that tells the compiler to perform specific mathematical
or logical manipulations. C/C++/Java is rich in built-in operators and provide the
following types of operators –
o Arithmetic Operators
o Relational Operators
o Logical Operators
o Bitwise Operators
o Assignment Operators
o Miscellaneous Operators
• Arithmetic Operators
There are following arithmetic operators supported by C/C++/Java
language. Assume variable A holds 10 and variable B holds 20, then –
• Relational Operators
There are following relational operators supported by C/C++/Java
language. Assume variable A holds 10 and variable B holds 20, then –
• Logical Operators
There are following logical operators supported by C/C++/Java
language. Assume variable A holds 1 and variable B holds 0, then –
• Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth
tables for &, |, and ^ are as follows −
1 0 0 1 1
Assume A = 60; and B = 13; now in binary format they will be as follows-
A = 0011 1100
B = 0000 1101
• Assignment Operators
There are following assignment operators supported by C/C++/Java
language −
C >>= 2 is same as
>>= Right shift AND assignment operator.
C = C >> 2
C &= 2 is same as C
&= Bitwise AND assignment operator.
=C&2
bitwise exclusive OR and assignment C ^= 2 is same as C
^=
operator. =C^2
bitwise inclusive OR and assignment C |= 2 is same as C
|=
operator. =C|2
• Miscellaneous Operators
The following table lists some other operators that C++ supports.
1 Sizeof
sizeof operator returns the size of a variable. For example, sizeof(a),
where ‘a’ is integer, and will return 4.
2 Condition ? X : Y
Conditional operator (?). If Condition is true then it returns value of X
otherwise returns value of Y. It is also called as ternary operator.
3 ,
Comma operator causes a sequence of operations to be performed. The
value of the entire comma expression is the value of the last expression
of the comma-separated list.
Here, operators with the highest precedence appear at the top of the table,
those with the lowest appear at the bottom.
• Example -
The following example shows the operators’ precedence concept available
in C++.
#include <iostream>
using namespace std;
main() {
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
cout << "Value of (a + b) * c / d is :" << e << endl ;
e = ((a + b) * c) / d; // (30 * 15 ) / 5
cout << "Value of ((a + b) * c) / d is :" << e << endl ;
e = a + (b * c) / d; // 20 + (150/5)
cout << "Value of a + (b * c) / d is :" << e << endl ;
return 0;
}
When the above code is compiled and executed, it produces the following
result −
Value of (a + b) * c / d is :90
Value of ((a + b) * c) / d is :90
Value of (a + b) * (c / d) is :90
Value of a + (b * c) / d is :50
6. Constants/Literals
Constants refer to fixed values that the program may not alter and they are
called literals.
Constants can be of any of the basic data types and can be divided into Integer
Numerals, Floating-Point Numerals, Characters, Strings and Boolean Values.
Constants are treated just like regular variables except that their values cannot
be modified after their definition.
#include <iostream>
using namespace std;
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main() {
int area;
area = LENGTH * WIDTH;
cout << area;
cout << NEWLINE;
return 0;
}
When the above code is compiled and executed, it produces the following
result −
50
You can use const prefix to declare constants with specific type as follows-
#include <iostream>
using namespace std;
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
cout << area;
cout << NEWLINE;
return 0;
}
When the above code is compiled and executed, it produces the following
result −
50
The following is the correct order of data types from lower to higher rank:
bool → char → short int → int → unsigned int → long int → unsigned
long int → long long int → float → double → long double
#include <iostream>
using namespace std;
int main ()
{
short x = 200;
int y;
y = x;
cout << " Implicit Type Casting " << endl;
cout << " The value of x: " << x << endl;
Output:
In the next expressions, we declared an int type variable num is 20, and
the character type variable ch is 'a', which is equivalent to an integer value of
97. And then, we add these two variables to perform the implicit conversion,
which returns the result of the expression is 117.
Similarly, in the third expression, we add the integer variable num is 20,
and the character variable ch is 65, and then assign the result to the float
variable val. Thus, the result of the expression is automatically converted to
the float type by the compiler.
(type) expression;
type: It represents the user-defined data that converts the given expression.
int num;
num = (int) 4.534; // cast into int data type
cout << num;
When the above statements are executed, the floating-point value will be
cast into an integer data type using the cast () operator. And the float value
is assigned to an integer num that truncates the decimal portion and displays
only 4 as the integer value.
#include <iostream>
using namespace std;
int main ()
{
// declaration of the variables
int a, b;
float res;
a = 21;
b = 5;
cout << " Implicit Type Casting: " << endl;
cout << " Result: " << a / b << endl; // it loses some information
cout << " \n Explicit Type Casting: " << endl;
// use cast () operator to convert int data to float
res = (float) 21 / 5;
cout << " The value of float variable (res): " << res << endl;
return 0;
}
Output:
In the second expression, we declare a float type variable res that stores
the results of a and b without losing any data using the cast operator in the
explicit type cast method.
• Widening Casting
Example –
Output:
9
9.0
• Narrowing Casting
Example –
Output:
9
9.0
8. Escape Sequences
Output:
Output:
Hello GgPIT
Output:
Hello
CGPIT
Output:
Hello CGPIT
Output:
Hello friends
Welcome to GFG
Output:
endso fri
Output:
Hello\CGPIT
Output:
‘ Hello CGPIT
“ Hello CGPIT
Output:
??!
Output:
A:5
Explanation: Here ooo is one to three octal digits(0….7) means there must be
at least one octal digit after \ and maximum three. Here 072 is the octal
notation, first it is converted to decimal notation that is the ASCII value of char
‘:’. At the place of \072 there is : and the output is A:5.
Output:
BJ
Escape
Description
Character
\t It is used to insert a tab in the text at this point.
\' It is used to insert a single quote character in the text at this point.
\" It is used to insert a double quote character in the text at this point.
\r It is used to insert a carriage return in the text at this point.
\\ It is used to insert a backslash character in the text at this point.
\n It is used to insert a new line in the text at this point.
\f It is used to insert a form feed in the text at this point.
\b It is used to insert a backspace in the text at this point.
Output:
Output:
Output:
Output:
Output:
Output:
Output:
Output:
\- this is a backslash.
9. Input/Output
If bytes flow from main memory to device like printer, display screen, or a
network connection, etc, this is called as output operation.
If bytes flow from device like printer, display screen, or a network connection,
etc to main memory, this is called as input operation.
#include <iostream>
using namespace std;
int main( ) {
char ary[] = "Welcome to CGPIT";
cout << "Value of ary is: " << ary << endl;
}
Output:
#include <iostream>
using namespace std;
int main( ) {
int age;
cout << "Enter your age: ";
cin >> age;
cout << "Your age is: " << age << endl;
}
Output:
#include <iostream>
using namespace std;
int main( ) {
cout << "Welcome to ";
cout << "CGPIT"<<endl;
cout << "UTU"<<endl;
}
Output:
Welcome to CGPIT
UTU
The cerr is also used in conjunction with the stream insertion operator as
shown in the following example.
#include <iostream>
using namespace std;
int main() {
char str[] = "Unable to read....";
cerr << "Error message : " << str << endl;
}
Output:
The clog is also used in conjunction with the stream insertion operator as
shown in the following example.
#include <iostream>
using namespace std;
int main() {
char str[] = "Unable to read....";
clog << "Error message : " << str << endl;
}
Output:
You would not be able to see any difference in cout, cerr and clog with these
small examples, but while writing and executing big programs the difference
becomes obvious. So it is good practice to display error messages using cerr
stream and while displaying other log messages then clog should be used.
To perform I/O operations faster, Java uses the concept of streams. A stream
can be defined as a sequence of data consisting of bytes.
The System class belongs to the “java.lang” package of Java. Apart from
providing standard I/O streams, System class also provides access to environment
variables, external variables, loading files and libraries, and also a utility method
arrayCopy for copying part of an array.
From Input-Output point of view, the System class offers the following streams:
The input stream provided by System class, System.in is used to read the
input data from a standard input device like a keyboard.
The stream remains open and is ready to read the data supplied by the
user to the standard input device.
The System.out interface of the System class is used to write the program
output to the standard output device like the monitor. In most cases, the
System.out interface writes the command output to the standard output device.
It uses three methods from the “PrintStream” class as the standard output
derives from this class.
o print
o println
o write
The methods “print” and “println” have the same functionality except for a
single difference that the println method appends a newline character (\n) to
the output.
The write method is not used frequently except in cases where non-ASCII
data is to be displayed.
Output:
Hello CGPIT!
I am learning Java.
It is awesome!
Hello CGPIT! I will print on the same line.
The standard error stream, System.err is used to display errors if any during
the execution of the program.
Like System.out stream, the error stream also supports the three methods of
PrintStream class, print, println and write.
The different methods using which we can read input data from the console in
Java are:
o Class BufferedReader
o Console Class
o Scanner
Class BufferedReader
The class BufferedReader was first introduced in JDK 1.0 and is the classical
method of reading input data from the console.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the input string");
String name = reader.readLine();
System.out.println("You entered: " + name);
}
}
Output:
Console Class
The class “System.console” can be used to read input from the console. This
is used to especially read input characters like a password from the command
line.
The method of reading input data using the console class is currently the
most efficient and preferred method in Java.
Output:
Using System.console class, you can read the input characters without
echoing the characters. Hence this method is more useful for reading
passwords. Secondly, you can also use format strings to format the input data,
similar to the ones used in System.out.printf ().
Although this is the preferred way of reading input data, note that the class
System.console cannot be used with an Interactive Java environment like IDEs.
Scanner
Using a scanner class to read input data is probably the fastest and
preferred method. The scanner is mostly used for parsing the data types
including primitive types and strings. But it can also be used to read the input
data and parse it using tokenized input.
The following program reads the input data from the user using the scanner
class.
import java.util.Scanner;
class Main
{
public static void main(String args[])
{
Scanner myscan = new Scanner(System.in);
System.out.println("Enter the input:");
String mystr = myscan.nextLine();
System.out.println("You entered a string: "+mystr);
System.out.println("Enter Next input:");
int num = myscan.nextInt();
System.out.println("You entered an integer: "+num);
}
}
Output:
In the above program, we have used the scanner class to read the string
and integer data.
The ios class contains several member functions that are used to perform
formatted IO operations.
The ios class also contains few format flags used to format the output. It has
format flags like showpos, showbase, oct, hex, etc. The format flags are
used by the function setf( ).
The following table provides the details of the functions of ios class used to
perform formatted IO in C++.
Function Description
width (int) Used to set the width in number of character spaces
for the immediate output data.
fill (char) Used to fill the blank spaces in output with given
character.
precision (int) Used to set the number of the decimal point to a float
value.
setf (format flags) Used to set various flags for formatting output like
showbase, showpos, oct, hex, etc.
unsetf (format flags) Used to clear the format flag setting.
All the above functions are called using the built-in object cout.
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
cout << "Example for formatted I/O" << endl;
cout << "Default: " << endl;
cout << 123 << endl;
cout << "width(5): " << endl;
cout.width(5);
cout << 123 << endl;
cout << "width(5) and fill('*'): " << endl;
cout.width(5);
cout.fill('*');
cout << 123 << endl;
cout.precision(5);
cout << "precision(5) ---> " << 123.4567890 << endl;
cout << "precision(5) ---> " << 9.876543210 << endl;
cout << "setf(showpos): " << endl;
cout.setf(ios::showpos);
cout << 123 << endl;
cout << "unsetf(showpos): " << endl;
cout.unsetf(ios::showpos);
cout << 123 << endl;
return 0;
}
Output:
The iomanip.h header file contains several special functions that are used
to perform formmated IO operations.
The following table provides the details of the special manipulator functions
used to perform formatted IO in C++.
Function Description
setw (int) Used to set the width in number of characters
for the immediate output data.
setfill (char) Used to fill the blank spaces in output with
given character.
setprecision (int) Used to set the number of digits of precision.
setbase (int) Used to set the number base.
setiosflags (format flags) Used to set the format flag.
resetiosflags (format flags) Used to clear the format flag.
The iomanip.h also contains the following format flags using in formatted
IO in C++.
Flag Description
endl Used to move the cursor position to a newline.
ends Used to print a blank space (null character).
dec Used to set the decimal flag.
oct Used to set the octal flag.
hex Used to set the hexadecimal flag.
left Used to set the left alignment flag.
right Used to set the right alignment flag.
showbase Used to set the showbase flag.
noshowbase Used to set the noshowbase flag.
showpos Used to set the showpos flag.
noshowpos Used to set the noshowpos flag.
showpoit Used to set the showpoit flag.
noshowpoint Used to set the noshowpoint flag.
#include <iostream>
#include <fstream>
using namespace std;
void line() {
cout << "-------------------------------" << endl;
}
int main()
{
cout << "Example for formatted IO" << endl;
line();
cout << "setw(10): " << endl;
cout << setw(10) << 99 << endl;
line();
cout << "setw(10) and setfill('*'): " << endl;
cout << setw(10) << setfill('*') << 99 << endl;
line();
cout << "setprecision(5): " << endl;
Output:
o Using System.out.printf()
o Using DecimalFormat class
o Using SimpleDateFormat class (for formatting Dates)
• Formatting output using System.out.printf()
This is the easiest of all methods as this is similar to printf in C. Note that
System.out.print() and System.out.println() take a single argument, but printf()
may take multiple arguments.
float n = 5.2f;
n = 2324435.3f;
Output:
Output:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
Output: