Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
142 views

FOP Unit-1 Part-2 (Introduction To Computer Programming)

This document provides an introduction to computer programming concepts like program structure, tokens, data types, variables, operators, and input/output in C++ and Java. It discusses the basic structure of C++ and Java programs, including main functions, headers, namespaces, comments, and how to compile and execute programs. It also covers programming elements like keywords, identifiers, constants, strings, special symbols, and operators. Data types in C++ and Java as well as variables, scopes, and types are explained. Finally, operators, constants, type conversion, escape sequences, and basic input/output are outlined.

Uploaded by

Viral Panchal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
142 views

FOP Unit-1 Part-2 (Introduction To Computer Programming)

This document provides an introduction to computer programming concepts like program structure, tokens, data types, variables, operators, and input/output in C++ and Java. It discusses the basic structure of C++ and Java programs, including main functions, headers, namespaces, comments, and how to compile and execute programs. It also covers programming elements like keywords, identifiers, constants, strings, special symbols, and operators. Data types in C++ and Java as well as variables, scopes, and types are explained. Finally, operators, constants, type conversion, escape sequences, and basic input/output are outlined.

Uploaded by

Viral Panchal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

Chhotubhai Gopalbhai Patel Institute of


Technology, Bardoli

Subject
Fundamentals of Programming (CE3002)

Unit – 1
Introduction of Computer Programming
(Part – 2)

Prepared by – Mr. Viral H. Panchal 1


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

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

Prepared by – Mr. Viral H. Panchal 2


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

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.

1.1. C++ Program Structure


Let us look at a simple C++ code that would print the words Hello World.

#include <iostream>
using namespace std;

// main() is where program execution begins.


int main() {
cout << "Hello World"; // prints Hello World
return 0;
}

Let us look at the various parts of the above program −

• 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.

Prepared by – Mr. Viral H. Panchal 3


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

• 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.

1.2. Compile and Execute C++ Program


Let's look at how to save the file, compile and run the program. Follow the
steps given below −

• Open a text editor and add the code as above.


• Save the file as: hello.cpp
• Open a command prompt and go to the directory where you saved the
file.
• Type 'g++ hello.cpp' and press enter to compile your code. If there are no
errors in your code the command prompt will take you to the next line and
would generate a.out executable file.
• Now, type 'a.out' to run your program.
• You will be able to see ' Hello World ' printed on the window.

$ 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.

Prepared by – Mr. Viral H. Panchal 4


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

1.3. Java Program Structure


Let us look at a simple Java code that will print the words Hello World.

public class MyFirstJavaProgram {

/* This is my first java program.


* This will print 'Hello World' as the output
*/

public static void main(String[] args) {


System.out.println("Hello World"); // prints Hello World
}
}

About Java programs, it is very important to keep in mind the following points.

• Case Sensitivity − Java is case sensitive, which means


identifier Hello and hello would have different meaning in Java.
• Class Names − For all class names the first letter should be in Upper Case.
If several words are used to form a name of the class, each inner word's
first letter should be in Upper Case.

Example: class MyFirstJavaClass

• 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.

Example: public void myMethodName()

• 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).

Prepared by – Mr. Viral H. Panchal 5


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

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.

Example: Assume 'MyFirstJavaProgram' is the class name. Then the file


should be saved as 'MyFirstJavaProgram.java'

• public static void main(String[] args) − Java program processing starts


from the main() method which is a mandatory part of every Java program.

1.4. Compile and Execute Java Program


Let's look at how to save the file, compile, and run the program. Follow the
subsequent steps −

• Open notepad and add the code as above.


• Save the file as: MyFirstJavaProgram.java.
• Open a command prompt window and go to the directory where you saved
the class. Assume it's C:\.
• Type 'javac MyFirstJavaProgram.java' and press enter to compile your
code. If there are no errors in your code, the command prompt will take
you to the next line (Assumption : The path variable is set).
• Now, type ' java MyFirstJavaProgram ' to run your program.
• You will be able to see ' Hello World ' printed on the window.

C:\> javac MyFirstJavaProgram.java


C:\> java MyFirstJavaProgram
Hello World

Prepared by – Mr. Viral H. Panchal 6


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

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.

A list of 32 Keywords in C++ Language which are also available in C


language are given below.

auto break case char const continue default do

double else enum extern float for goto if

int long register return short signed sizeof static

struct switch typedef union unsigned void volatile while

A list of 30 Keywords in C++ Language which are not available in C language


are given below.
asm dynamic_cast namespace reinterpret_cast bool

explicit new static_cast false catch

operator template friend private class

this inline public throw const_cast

delete mutable protected true try

typeid typename using virtual wchar_t

Prepared by – Mr. Viral H. Panchal 7


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

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.

• Rules for C++ Identifiers

There are certain rules to be followed by the user while naming identifiers,
otherwise, you would get a compilation error. These rules are:

o They must begin with a letter or underscore ( _ ).


o They must consist of only letters, digits, or underscore. No other special
character is allowed.
o It should not be a keyword.
o It must not contain white space.
o It should be up to 31 characters long as only the first 31 characters are
significant.

The following are the examples of valid identifiers are:


Result
Test2
_sum
power
The following are the examples of invalid identifiers:
Sum-1 // containing special character '-'.
2data // the first letter is a digit.
break // use of a keyword.

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.

Prepared by – Mr. Viral H. Panchal 8


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

Syntax: const data_type variable_name;

• Types of Constants

The different types of constants are:

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.

In C++, a string can be declared in the following ways:

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

Prepared by – Mr. Viral H. Panchal 9


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

2.5. Special Symbols


The following special symbols are used in C/C++ having some special
meaning and thus cannot be used for some other purpose.

• 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.

Prepared by – Mr. Viral H. Panchal 10


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

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

Prepared by – Mr. Viral H. Panchal 11


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

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.

C++ supports the following data types:


• Primary or Built-in or Fundamental data type
• Derived data types
• User defined data types

Prepared by – Mr. Viral H. Panchal 12


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

3.1. Primary or Built-in or Fundamental Data Types


C++ offers the programmer a rich assortment of built-in as well as user
defined data types. Following table lists down seven basic C++ data types −

Type Keyword
Boolean bool
Character char
Integer int

Floating point float


Double floating point double
Valueless void

Wide character wchar_t

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.

Prepared by – Mr. Viral H. Panchal 13


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

Type Typical Size Typical Range


char or signed char 1 byte (8 bits) -128 to 127

unsigned char 1 byte (8 bits) 0 to 255


int or signed int 2 bytes (16 bits) -32768 to 32767 (-215 to 215 - 1
unsigned int 2 bytes (16 bits) 0 to 65,535 (0 to 216 -1)
short int or signed 2 bytes (16 bits) -32768 to 32767 (-215 to 215 - 1)
short int
unsigned short int 2 bytes (16 bits) 0 to 65,535 (0 to 216 -1)
long int or signed 4 bytes (32 bits) -2147483648 to 2147483647
long int (-231 to 231-1)
unsigned long int 4 bytes (32 bits) 0 to 4294967295 (0 to 232 – 1)

float 4 bytes (32 bits) 3.4e-38 to 3.4e+38


double 8 bytes (64 bits) 1.7e-308 to 1.7e+308
long double 10 bytes (80 bits) 3.4e-4932 to 1.1e+4932

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.

Prepared by – Mr. Viral H. Panchal 14


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

#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

3.2. Derived Data Types


The data types that are derived from the primitive or built-in datatypes are
referred to as Derived Data Types. These can be of four types namely:

o Function
o Array
o Pointer
o Reference

Prepared by – Mr. Viral H. Panchal 15


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

3.3. Abstract or User-Defined Data Types


These data types are defined by the user itself. Like, as defining a class in
C++ or a structure. C++ provides the following user-defined datatypes:

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 −

typedef type newname;

For example, the following declaration tells the compiler that feet is another
name for int –

typedef int feet;

Now, the following declaration is perfectly legal and creates an integer


variable called distance −

feet distance;

• Enumerated Types

An enumerated type declares an optional type name and a set of zero or


more identifiers that can be used as values of the type. Each enumerator is a
constant whose type is the enumeration.

Creating an enumeration requires the use of the keyword enum. The general
form of an enumeration type is −

Prepared by – Mr. Viral H. Panchal 16


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

enum enum-name { list of names } var-list;

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".

enum color { red, green, blue } c;


c = 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.

enum color { red, green = 5, blue };

Here, blue will have a value of 6 because each name will be one greater than
the one that precedes it.

3.4. Data Types in Java


There are two types of data types in Java:

o Primitive Data Types


o Reference/Object Data Types

• Primitive Data Types

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 Byte data type is an 8-bit signed two's complement integer.


o Minimum value is -128 (-2^7).
o Maximum value is 127 (inclusive)(2^7 -1).
Prepared by – Mr. Viral H. Panchal 17
Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

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

o Short data type is a 16-bit signed two's complement integer.


o Minimum value is -32,768 (-2^15).
o Maximum value is 32,767 (inclusive) (2^15 -1).
o Short data type can also be used to save memory as byte data type.
A short is 2 times smaller than an integer.
o Default value is 0.
o Example: short s = 10000, short r = -20000

int

o Int data type is a 32-bit signed two's complement integer.


o Minimum value is - 2,147,483,648 (-2^31).
o Maximum value is 2,147,483,647(inclusive) (2^31 -1).
o Integer is generally used as the default data type for integral values
unless there is a concern about memory.
o The default value is 0.
o Example: int a = 100000, int b = -200000

long

o Long data type is a 64-bit signed two's complement integer.


o Minimum value is -9,223,372,036,854,775,808 (-2^63).
o Maximum value is 9,223,372,036,854,775,807 (inclusive) (2^63 -1).
o This type is used when a wider range than int is needed.
o Default value is 0L.
o Example: long a = 100000L, long b = -200000L

Prepared by – Mr. Viral H. Panchal 18


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

float

o Float data type is a single-precision 32-bit IEEE 754 floating point.


o Float is mainly used to save memory in large arrays of floating-point
numbers.
o Default value is 0.0f
o Float data type is never used for precise values such as currency.
o Example: float f1 = 234.5f

double

o double data type is a double-precision 64-bit IEEE 754 floating point.


o This data type is generally used as the default data type for decimal
values, generally the default choice.
o Double data type should never be used for precise values such as
currency.
o Default value is 0.0d
o Example: double d1 = 123.4

boolean

o boolean data type represents one bit of information.


o There are only two possible values: true and false.
o This data type is used for simple flags that track true/false conditions.
o Default value is false.
o Example: boolean one = true

char

o char data type is a single 16-bit Unicode character.


o Minimum value is '\u0000' (or 0). The \u0000 is the lowest range of
Unicode system. Java uses Unicode system not ASCII code system.
o Maximum value is '\uffff' (or 65,535 inclusive).
o Char data type is used to store any character.
o Example: char letterA = 'A'

Prepared by – Mr. Viral H. Panchal 19


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

• Reference/Object Data Types

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.

Default value of any reference variable is null.

A reference variable can be used to refer any object of the declared type or
any compatible type.

Example: Animal animal = new Animal("giraffe");

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.

4.1. Variable Definition in C++


A variable definition tells the compiler where and how much storage to create
for the variable. A variable definition specifies a data type, and contains a list
of one or more variables of that type as follows −
Prepared by – Mr. Viral H. Panchal 20
Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

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.

Variables can be initialized (assigned an initial value) in their declaration. The


initializer consists of an equal sign followed by a constant expression as follows -

type variable_name = value;

Some examples are −

extern int d = 3, f = 5; // declaration of d and f.


int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.

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.

4.2. Variable Declaration in C++


A variable declaration provides assurance to the compiler that there is one
variable existing with the given type and name so that compiler proceed for
further compilation without needing complete detail about the variable. A
variable declaration has its meaning at the time of compilation only, compiler
needs actual variable definition at the time of linking of the program.

Prepared by – Mr. Viral H. Panchal 21


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

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

Prepared by – Mr. Viral H. Panchal 22


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

• Lvalues and Rvalues


There are two kinds of expressions in C++.

o lvalue − Expressions that refer to a memory location is called "lvalue"


expression. An lvalue may appear as either the left-hand or right-hand
side of an assignment.
o rvalue − The term rvalue refers to a data value that is stored at some
address in memory. An rvalue is an expression that cannot have a value
assigned to it which means an rvalue may appear on the right- but not left-
hand side of an assignment.

Variables are lvalues and so may appear on the left-hand side of an


assignment. Numeric literals are rvalues and so may not be assigned and can
not appear on the left-hand side. Following is a valid statement −

int g = 20;

But the following is not a valid statement and would generate compile-time
error −

10 = 20;

4.3. Variable Scope in C++


A scope is a region of the program where variables can be declared and
there are three places where variables can be declared −

o Inside a function or a block which is called local variables


o In the definition of function parameters which is called formal
parameters.
o Outside of all functions which is called global variables.
• Local Variables
Variables that are declared inside a function or block are local variables.
They can be used only by statements that are inside that function or block of
code. Local variables are not known to functions outside their own.

Prepared by – Mr. Viral H. Panchal 23


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

Following is the example using local variables –

#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.

A global variable can be accessed by any function. That is, a global


variable is available for use throughout your entire program after its
declaration.

Following is the example using global and local variables –

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

Prepared by – Mr. Viral H. Panchal 24


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

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

• Initializing Local and Global Variables


When a local variable is defined, it is not initialized by the system, you
must initialize it yourself. Global variables are initialized automatically by the
system when you define them as follows −

Data Type Initializer


int 0
char '\0'
float 0
double 0
pointer NULL

It is a good programming practice to initialize variables properly,


otherwise sometimes program would produce unexpected result.

Prepared by – Mr. Viral H. Panchal 25


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

4.4. Types of Variables in Java


There are three types of variables in Java:
o Local Variables
o Instance Variables
o Classic/Static Variables
• Local Variables
A variable declared inside the body of the method is called local variable.
You can use this variable only within that method and the other methods in the
class aren't even aware that the variable exists.

A local variable cannot be defined with "static" keyword.

• 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.

It is called an instance variable because its value is instance-specific and is


not shared among instances.

• 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.

• Example to understand the types of variables in java


public class A {
static int m=100;//static variable
void method() {
int n=90;//local variable
}
public static void main(String args[]) {
int data=50;//instance variable
}
}//end of class

Prepared by – Mr. Viral H. Panchal 26


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

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 –

Operator Description Example


+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiplies both operands A * B will give 200
/ Divides numerator by de-numerator B / A will give 2
Modulus Operator and remainder of
% B % A will give 0
after an integer division

Increment operator, increases integer


++ A++ will give 11
value by one
Decrement operator, decreases integer
-- A-- will give 9
value by one

• Relational Operators
There are following relational operators supported by C/C++/Java
language. Assume variable A holds 10 and variable B holds 20, then –

Prepared by – Mr. Viral H. Panchal 27


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

Operator Description Example


== Checks if the values of two operands are (A == B) is not true.
equal or not, if yes then condition becomes
true.
!= Checks if the values of two operands are (A != B) is true.
equal or not, if values are not equal then
condition becomes true.
> Checks if the value of left operand is (A > B) is not true.
greater than the value of right operand, if
yes then condition becomes true.
< Checks if the value of left operand is less (A < B) is true.
than the value of right operand, if yes then
condition becomes true.

>= Checks if the value of left operand is (A >= B) is not true.


greater than or equal to the value of right
operand, if yes then condition becomes true.
<= Checks if the value of left operand is less (A <= B) is true.
than or equal to the value of right operand,
if yes then condition becomes true.

• Logical Operators
There are following logical operators supported by C/C++/Java
language. Assume variable A holds 1 and variable B holds 0, then –

Operator Description Example


&& Called Logical AND operator. If both the (A && B) is false.
operands are non-zero, then condition
becomes true.
|| Called Logical OR Operator. If any of the (A || B) is true.
two operands is non-zero, then condition
becomes true.
! Called Logical NOT Operator. Use to !(A && B) is true.
reverses the logical state of its operand. If
a condition is true, then Logical NOT
operator will make false.

Prepared by – Mr. Viral H. Panchal 28


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

• Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth
tables for &, |, and ^ are as follows −

p q p&q p|q p^q


0 0 0 0 0
0 1 0 1 1
1 1 1 1 0

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

A&B = 0000 1100


A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011

The following are the Bitwise operators supported by C/C++/Java


language. Assume variable A holds 60 and variable B holds 13, then −

Operator Description Example


& Binary AND Operator copies a
(A & B) will give 12 which is
bit to the result if it exists in both
0000 1100
operands.

| Binary OR Operator copies a bit (A | B) will give 61 which is


if it exists in either operand. 0011 1101
^ Binary XOR Operator copies the
(A ^ B) will give 49 which is
bit if it is set in one operand but
0011 0001
not both.

Prepared by – Mr. Viral H. Panchal 29


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

~ Binary One’s Complement (~A ) will give -61 which is


Operator is unary and has the 1100 0011 in 2's complement
effect of 'flipping' bits. form due to a signed binary
number.
<< Binary Left Shift Operator. The
left operands value is moved A << 2 will give 240 which is
left by the number of bits 1111 0000
specified by the right operand.

>> Binary Right Shift Operator. The


left operands value is moved A >> 2 will give 15 which is
right by the number of bits 0000 1111
specified by the right operand.

• Assignment Operators
There are following assignment operators supported by C/C++/Java
language −

Operator Description Example


Simple assignment operator. Assigns values C = A + B will assign
=
from right side operands to left side operand. value of A + B into C

Add AND assignment operator. It adds right


C += A is equivalent
+= operand to the left operand and assign the
to C = C + A
result to left operand.
Subtract AND assignment operator. It
C -= A is equivalent
-= subtracts right operand from the left operand
to C = C – A
and assign the result to left operand.
Multiply AND assignment operator. It
C *= A is equivalent
*= multiplies right operand with the left operand
to C = C * A
and assign the result to left operand.

/= Divide AND assignment operator. It divides


C /= A is equivalent
left operand with the right operand and
to C = C / A
assign the result to left operand.
Modulus AND assignment operator. It takes
C %= A is equivalent
%= modulus using two operands and assign the
to C = C % A
result to left operand.
C <<= 2 is same as
<<= Left shift AND assignment operator.
C = C << 2

Prepared by – Mr. Viral H. Panchal 30


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

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.

Sr.No Operator & Description

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.

4 . (dot) and -> (arrow)


Member operators are used to reference individual members of classes,
structures, and unions.
5 Cast
Casting operators convert one data type to another. For example,
int(2.2000) would return 2.
6 &
Pointer operator & returns the address of a variable. For example, &a;
will give actual address of the variable.
7 *
Pointer operator * is pointer to a variable. For example, *var; will
pointer to a variable var.

Prepared by – Mr. Viral H. Panchal 31


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

5.1. Operators Precedence and Associativity


Operator precedence determines the grouping of terms in an expression. This
affects how an expression is evaluated. Certain operators have higher
precedence than others; for example, the multiplication operator has higher
precedence than the addition operator. Within an expression, higher precedence
operators will be evaluated first.

For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator


* has higher precedence than.

Here, operators with the highest precedence appear at the top of the table,
those with the lowest appear at the bottom.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right


Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right

Prepared by – Mr. Viral H. Panchal 32


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

• 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); // (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

Prepared by – Mr. Viral H. Panchal 33


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

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.

6.1. Defining Constants


There are two simple ways in C++ to define constants −

o Using #define preprocessor


o Using const keyword

• The #define Preprocessor

Following is the form to use #define preprocessor to define a constant −

#define identifier value

Following example explains it in detail −

#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

Prepared by – Mr. Viral H. Panchal 34


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

• The const Keyword

You can use const prefix to declare constants with specific type as follows-

const type variable = value;

Following example explains it in detail −

#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

Note that it is a good programming practice to define constants in


CAPITALS.

Prepared by – Mr. Viral H. Panchal 35


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

7. Type Conversion/Type Casting

7.1. Type Conversion/Type Casting in C++


A type cast is basically a conversion from one type to another. There are two
types of type conversion:

o Implicit Type Conversion


o Explicit Type Conversion

• Implicit Type Conversion or Implicit Type Casting


o It is known as the automatic type casting.
o It automatically converted from one data type to another without any
external intervention such as programmer or user. It means the compiler
automatically converts one data type to another.
o All data type is automatically upgraded to the largest type without
losing any information.
o It can only apply in a program if both variables are compatible with
each other.

Order of the typecast in implicit conversion –

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

Program to demonstrate the use of the implicit type casting –

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

Prepared by – Mr. Viral H. Panchal 36


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

cout << " The value of y: " << y << endl;


int num = 20;
char ch = 'a';
int res = 20 + 'a';
cout << " Type casting char to int data type ('a' to 20): "
<< res << endl;
float val = num + 'A';
cout << " Type casting from int data to float type: " << val
<< endl;
return 0;
}

Output:

Implicit Type Casting


The value of x: 200
The value of y: 200
Type casting char to int data type ('a' to 20): 117
Type casting from int data to float type: 85

In the above program, we declared a short data type variable x is 200


and an integer variable y. After that, we assign x value to the y, and then the
compiler automatically converts short data value x to the y, which returns y is
200.

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.

Prepared by – Mr. Viral H. Panchal 37


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

• Explicit Type Conversion or Explicit Type Casting


o It is also known as the manual type casting in a program.
o It is manually cast by the programmer or user to change from one data
type to another type in a program. It means a user can easily cast one
data to another according to the requirement in a program.
o It does not require checking the compatibility of the variables.
o In this casting, we can upgrade or downgrade the data type of one
variable to another in a program.
o It uses the cast () operator to change the type of a variable.

Syntax of the explicit type casting –

(type) expression;

type: It represents the user-defined data that converts the given expression.

expression: It represents the constant value, variable, or an expression


whose data type is converted.

For example, we have a floating pointing number is 4.534, and to convert


an integer value, the statement as:

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.

Program to demonstrate the use of the explicit type casting –

#include <iostream>
using namespace std;
int main ()
{
// declaration of the variables
int a, b;

Prepared by – Mr. Viral H. Panchal 38


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

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:

Implicit Type Casting:


Result: 4

Explicit Type Casting:


The value of float variable (res): 4.2

In the above program, we take two integer variables, a and b, whose


values are 21 and 5. And then, divide a by b (21/5) that returns a 4 int type
value.

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.

7.2. Type Conversion/Type Casting in Java


In Java, there are two types of casting:

• Widening Casting (automatically) - converting a smaller type to a larger type


byte → short → char → int → long → float → double

• Narrowing Casting (manually) - converting a larger type to a smaller type


double → float → long → int → char → short → byte

Prepared by – Mr. Viral H. Panchal 39


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

• Widening Casting

Widening casting is done automatically when passing a smaller size type


to a larger size type.

Example –

public class Main {


public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}

Output:

9
9.0

• Narrowing Casting

Narrowing casting must be done manually by placing the type in


parentheses in front of the value:

Example –

public class Main {


public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int
System.out.println(myDouble); // Outputs 9.78
System.out.println(myInt); // Outputs 9
}
}

Output:

9
9.0

Prepared by – Mr. Viral H. Panchal 40


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

8. Escape Sequences

8.1. Escape Sequences in C/C++


In C/C++ programming language, there are 256 numbers of characters in
character set. The entire character set is divided into two parts i.e., the ASCII
characters set and the extended ASCII characters set. But apart from that, some
other characters are also there which are not the part of any characters set, known
as ESCAPE characters.

• List of Escape Sequences in C/C++

Escape Character Meaning


\a Alarm or Beep
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Tab (Horizontal)
\v Vertical Tab
\\ Backslash
\' Single Quote
\" Double Quote
\? Question Mark
\ooo octal number
\xhh hexadecimal number
\0 Null

Prepared by – Mr. Viral H. Panchal 41


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

• C Escape Sequence Examples

// C program to illustrate \a escape sequence


#include <stdio.h>
int main(void)
{
printf("My mobile number "
"is 7\a8\a7\a3\a9\a2\a3\a4\a0\a8\a");
return (0);
}

Output:

My mobile number is 7873923408

// C program to illustrate \b escape sequence


#include <stdio.h>
int main(void)
{
// \b - backspace character transfers
// the cursor one character back with
// or without deleting on different
// compilers.
printf("Hello CGPIT\b\b\b\bg");
return (0);
}

Output:

Hello GgPIT

// C program to illustrate \n escape sequence


#include <stdio.h>
int main(void)
{
// Here we are using \n, which
// is a new line character.
printf("Hello\n");
printf("CGPIT");
return (0);
}

Prepared by – Mr. Viral H. Panchal 42


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

Output:

Hello
CGPIT

// C program to illustrate \t escape sequence


#include <stdio.h>
int main(void)
{
// Here we are using \t, which is a horizontal tab
//character. It will provide a tab space between two words.
printf("Hello \t CGPIT");
return (0);
}

Output:

Hello CGPIT

// C program to illustrate \v escape sequence


#include <stdio.h>
int main(void)
{
// Here we are using \v, which is vertical tab character.
printf("Hello friends");
printf("\v Welcome to CGPIT");
return (0);
}

Output:

Hello friends
Welcome to GFG

// C program to illustrate \r escape sequence


#include <stdio.h>
int main(void)
{
// Here we are using \r, which is carriage return character.
printf("Hello fri \rends");
return (0);
}

Prepared by – Mr. Viral H. Panchal 43


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

Output:

endso fri

// C program to illustrate \\(Backslash)


// escape sequence to print backslash.
#include <stdio.h>
int main(void)
{
// Here we are using \\, which is backslash character.
printf("Hello\\CGPIT");
return (0);
}

Output:

Hello\CGPIT

// C program to illustrate \' escape sequence and \" escape


// sequence to print single quote and double quote.
#include <stdio.h>
int main(void)
{
printf("\' Hello CGPIT\n");
printf("\" Hello CGPIT");
return 0;
}

Output:

‘ Hello CGPIT
“ Hello CGPIT

// C program to illustrate \? escape sequence


#include <stdio.h>
int main(void)
{
// Here we are using \?, which is question mark charcter.
printf("\?\?!\n");
return 0;
}

Output:

??!

Prepared by – Mr. Viral H. Panchal 44


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

// C program to illustrate \OOO escape sequence


#include <stdio.h>
int main(void)
{
// we are using \OOO escape sequence, here each O in "OOO"
// is one to three octal digits(0....7).
char* s = "A\072\065";
printf("%s", s);
return 0;
}

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.

// C program to illustrate \XHH escape sequence


#include <stdio.h>
int main(void)
{
// We are using \xhh escape sequence. Here hh is one or more
// hexadecimal digits(0....9, a...f, A...F).
char* s = "B\x4a";
printf("%s", s);
return 0;
}

Output:

BJ

Explanation: Here hh is one or more hexadecimal digits(0….9, a…f,


A…F).There can be more than one hexadecimal number after \x. Here, ‘\x4a’
is a hexadecimal number and it is a single char. Firstly it will get converted
into decimal notation and it is the ASCII value of char ‘J’. Therefore, at the
place of \x4a, we can write J. So the output is BJ.

Prepared by – Mr. Viral H. Panchal 45


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

8.2. Escape Sequences in Java


In Java, there is a total of eight escape sequences that are described in the
following table.

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.

• Java Escape Sequence Examples


// \t -> It gives a tab between two words.
public class Main {
public static void main(String[] args)
{
System.out.println("Good Morning\t CGPIT! ");
}
}

Output:

Good Morning CGPIT!

// The escape sequence \b is a backspace character


// It moves the cursor one character back with
// or without deleting the character(depending upon compiler)
public class Main {
public static void main(String[] args)
{
System.out.println("Good Morning C\bGPIT! ");
}
}

Output:

Good Morning GPIT!

Prepared by – Mr. Viral H. Panchal 46


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

// This \n escape sequence is for a new line.


public class Main {
public static void main(String[] args)
{
System.out.println("Good Morning CGPIT!\nHow are you all?");
}
}

Output:

Good Morning CGPIT!


How are you all?

// This \r escape sequence is a carriage return character


// It moves the output point back to the beginning of the line
// without moving down a line (usually).
public class Main {
public static void main(String[] args)
{
System.out.print("Gita is going to Market\rS");
}
}

Output:

Sita is going to Market

// This \f escape sequence is a form feed character


// It is an old technique and used to indicate a page break.
public class Main {
public static void main(String[] args)
{
System.out.println("Good Morning CGPIT!\fHow are you all?");
}
}

Output:

Good Morning CGPIT!


How are you all?

Prepared by – Mr. Viral H. Panchal 47


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

// This \' escape sequence is for printing a single quotation


mark on the text string
public class Main {
public static void main(String[] args)
{
System.out.println("Good Morning \CGPIT!\'");
}
}

Output:

Good Morning 'CGPIT!'

// This \" escape sequence is for printing a double quotation


mark on the text string
public class Main {
public static void main(String[] args)
{
System.out.println("Good Morning \"CGPIT!\"");
}
}

Output:

Good Morning “CGPIT!”

// This \\ escape sequence is for printing a backslash on the


text string
public class Main {
public static void main(String[] args)
{
System.out.println("\\- this is a backslash.");
}
}

Output:

\- this is a backslash.

Prepared by – Mr. Viral H. Panchal 48


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

9. Input/Output

9.1. C++ Basic Input/Output


C++ I/O operation is using the stream concept. Stream is the sequence of
bytes or flow of data. It makes the performance fast.

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.

• I/O Library Header Files

The common header files used in C++ programming are:

Header File Function and Description


<iostream> This file defines the cin, cout, cerr and clog objects, which
correspond to the standard input stream, the standard output
stream, the un-buffered standard error stream and the buffered
standard error stream, respectively.
<iomanip> This file declares services useful for performing formatted I/O with
so-called parameterized stream manipulators, such as setw and
setprecision
<fstream> This file declares services for user-controlled file processing.

• The Standard Output Stream (cout)

The cout is a predefined object of ostream class. It is connected with the


standard output device, which is usually a display screen. The cout is used in
conjunction with stream insertion operator (<<) to display the output on a
console.

The simple example of standard output stream (cout) –

Prepared by – Mr. Viral H. Panchal 49


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

#include <iostream>
using namespace std;
int main( ) {
char ary[] = "Welcome to CGPIT";
cout << "Value of ary is: " << ary << endl;
}

Output:

Value of ary is: Welcome to CGPIT

• The 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.

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

Output:

Enter your age: 18


Your age is: 18

Prepared by – Mr. Viral H. Panchal 50


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

• The Standard End Line (endl)

The endl is a predefined object of ostream class. It is used to insert a


new line character and flushes the stream.

The simple example of standard end line (endl) –

#include <iostream>
using namespace std;
int main( ) {
cout << "Welcome to ";
cout << "CGPIT"<<endl;
cout << "UTU"<<endl;
}

Output:

Welcome to CGPIT
UTU

• The Standard Error Stream (cerr)

The predefined object cerr is an instance of ostream class. The cerr


object is said to be attached to the standard error device, which is also a
display screen but the object cerr is un-buffered and each stream insertion to
cerr causes its output to appear immediately.

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:

Error message : Unable to read....

Prepared by – Mr. Viral H. Panchal 51


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

• The Standard Log Stream (clog)

The predefined object clog is an instance of ostream class. The clog


object is said to be attached to the standard error device, which is also a
display screen but the object clog is buffered. This means that each insertion
to clog could cause its output to be held in a buffer until the buffer is filled or
until the buffer is flushed.

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:

Error message : Unable to read....

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.

9.2. Java Basic Input/Output


Java I/O (Input-Output) is a standard mechanism that processes the input and
generates the output. The package “java.io” contains the methods to perform all
the input and output operations.

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.

Prepared by – Mr. Viral H. Panchal 52


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

• Standard I/O Streams in Java

Java language offers access to system resources, standard input-output


devices, etc. using a “System” class. This class implements a system-dependent
programming interface to access various resources.

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:

o Standard Input Stream (System.in)


o Standard Output Stream (System.out)
o Standard Error Stream (System.err)

Standard Input Stream (System.in) –

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 below example demonstrates the System.in.read function.

public class Main {


public static void main(String args[]) throws java.io.IOException {
int ch;
System.out.println("Enter the character to be displayed : ");
ch = System.in.read();
System.out.println("You entered : " + (char)ch);
}
}
Output:
Enter the character to be displayed :
V
You entered : V

Prepared by – Mr. Viral H. Panchal 53


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

Standard Output Stream (System.out) –

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.

These methods are:

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.

The following example demonstrates the System.out stream.

public class Main {


public static void main(String args[]) throws java.io.IOException {
System.out.println("Hello CGPIT!");
System.out.println("I am learning Java.");
System.out.println("It is awesome!");
System.out.print("Hello CGPIT! ");
System.out.print("I will print on the same line.");
}
}

Output:

Hello CGPIT!
I am learning Java.
It is awesome!
Hello CGPIT! I will print on the same line.

Prepared by – Mr. Viral H. Panchal 54


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

Standard Error Stream (System.err) –

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.

• Methods To Read Input from the Console

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.

The input stream (System.in) is wrapped inside the class InputStreamReader


which is in turn wrapped in BufferedReader.

The following program shows the usage of the BufferedReader class to


read input data from the user.

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

Prepared by – Mr. Viral H. Panchal 55


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

Output:

Enter the input string


Welcome to CGPIT
You entered: Welcome to CGPIT

In the above program, we have declared an object of BufferedReader


class initialized to System.in stream. Using this object, we read an entire line
of input.

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.

The following program demonstrates the System.console class.

public class Main {


public static void main(String[] args)
{
System.out.println("Enter the input string");
String name = System.console().readLine();
System.out.println("You entered: " + name);
}
}

Output:

Enter the input string


Welcome to CGPIT
You entered: Welcome to CGPIT

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 ().

Prepared by – Mr. Viral H. Panchal 56


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

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 scanner class uses regular expressions for this purpose.

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:

Enter the input:


Welcome to CGPIT
You entered a string: Welcome to CGPIT
Enter Next input:
2500
You entered an integer: 2500

In the above program, we have used the scanner class to read the string
and integer data.

Prepared by – Mr. Viral H. Panchal 57


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

9.3. Formatted I/O in C++


The C++ programming language provides the several built-in functions to
display the output in formatted form. These built-in functions are available in
the header file iomanip.h and ios class of header file iostream.h.

In C++, there are two ways to perform the formatted IO operations.

o Using the member functions of ios class.


o Using the special functions called manipulators defined in iomanip.h.

• Formatted I/O using ios Class Members

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.

Prepared by – Mr. Viral H. Panchal 58


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

Lets look at the following code to illustrate the formatted IO operations


using member functions of ios class.

Example - Code to illustrate the formatted IO using ios class

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

Prepared by – Mr. Viral H. Panchal 59


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

Output:

Example for formatted I/O


Default:
123
width(5):
123
width(5) and fill('*'):
**123
precision(5) ---> 123.46
precision(5) ---> 9.8765
setf(showpos):
+123
unsetf(showpos):
123

• Formatted I/O using Manipulators

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++.

Prepared by – Mr. Viral H. Panchal 60


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

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.

Lets look at the following code to illustrate the formatted IO operations


using manipulators.

Example - Code to illustrate the formatted IO using manipulators

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

Prepared by – Mr. Viral H. Panchal 61


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

cout << setprecision(5) << 123.4567890 << endl;


line();
cout << "showpos: " << endl;
cout << showpos << 999 << endl;
line();
cout << "hex: " << endl;
cout << hex << 100 << endl;
line();
cout << "hex and showbase: " << endl;
cout << showbase << hex << 100 << endl;
line();
return 0;
}

Output:

Example for formatted IO


-------------------------------
setw(10):
99
-------------------------------
setw(10) and setfill('*'):
********99
-------------------------------
setprecision(5):
123.46
-------------------------------
showpos:
+999
-------------------------------
hex:
64
-------------------------------
hex and showbase:
0x64
-------------------------------

Prepared by – Mr. Viral H. Panchal 62


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

9.4. Formatted I/O in Java


There are different ways in which we can format output in Java. Some of
them are given below.

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.

// Java program to demonstrate working of printf()


Public class JavaFormatter1 {
public static void main(String args[])
{
int x = 100;
System.out.printf("Printing simple integer: x = %d\n", x);

// this will print it upto 2 decimal places


System.out.printf("Formatted with precision: PI = %.2f\n",
Math.PI);

float n = 5.2f;

// automatically appends zero to the rightmost part


// of decimal
System.out.printf("Formatted to specific width: n = %.4f\n",
n);

n = 2324435.3f;

// here number is formatted from right margin and


// occupies a width of 20 characters
System.out.printf(
"Formatted to right margin: n = %20.4f\n", n);
}
}

Prepared by – Mr. Viral H. Panchal 63


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

Output:

Printing simple integer: x = 100


Formatted with precision: PI = 3.14
Formatted to specific width: n = 5.2000
Formatted to right margin: n = 2324435.2500

Note: System.out.format() is equivalent to printf() and can also be used.

• Formatting using DecimalFormat class

DecimalFormat is used to format decimal numbers.

// Java program to demonstrate working of DecimalFormat


import java.text.DecimalFormat;

public class JavaFormatter2 {


public static void main(String args[])
{
double num = 123.4567;

// prints only numeric part of a floating number


DecimalFormat ft = new DecimalFormat("####");
System.out.println("Without fraction part: num = "
+ ft.format(num));

// this will print it upto 2 decimal places


ft = new DecimalFormat("#.##");
System.out.println("Formatted to Give precision: num = "
+ ft.format(num));

// automatically appends zero to the rightmost part


// of decimal instead of #,we use digit 0
ft = new DecimalFormat("#.000000");
System.out.println("Appended zeroes to right: num = "
+ ft.format(num));

// automatically appends zero to the leftmost of


// decimal number instead of #,we use digit 0
ft = new DecimalFormat("00000.00");
System.out.println("Formatting numeric part: num = "
+ ft.format(num));

Prepared by – Mr. Viral H. Panchal 64


Fundamentals of Programming (CE3002) Unit – 1: Introduction of Computer Programming

// formatting money in dollars


double income = 23456.789;
ft = new DecimalFormat("$###,###.##");
System.out.println("Your formatted Income: "
+ ft.format(income));
}
}

Output:

Without fraction part: num = 123


Formatted to Give precision: num = 123.46
Appended zeroes to right: num = 123.456700
Formatting numeric part: num = 00123.46
Your formatted Income: $23,456.79

• Formatting dates and parsing using SimpleDateFormat class

This class is present in java.text package.

// Java program to demonstrate working of SimpleDateFormat

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Formatter3 {


public static void main(String args[]) throws ParseException
{
// Formatting as per given pattern in the argument
SimpleDateFormat ft = new SimpleDateFormat("dd-MM-yyyy");
String str = ft.format(new Date());
System.out.println("Formatted Date : " + str);
// parsing a given String
str = "02/18/1995";
ft = new SimpleDateFormat("MM/dd/yyyy");
Date date = ft.parse(str);
// this will print the date as per parsed string
System.out.println("Parsed Date : " + date);
}
}

Output:

Formatted Date : 06-10-2022


Parsed Date : Sat Feb 18 00:00:00 UTC 1995

Prepared by – Mr. Viral H. Panchal 65

You might also like