Unit III COMPUTER
Unit III COMPUTER
C++ was developed by BjarneStroustrup starting in 1979 at Bell Labs in Murray Hill,
New Jersey, as an enhancement to the C language and originally named C with
Classes but later it was renamed C++ in 1983.
C++ is a superset of C, and that virtually any legal C program is a legal C++
program.
C++ compilers
Borland C++
Turbo C++
Microsoft Visual C++
Zortech C++
UNIX C++ (AT&T)
GNU Compiler Collection (GCC)
Object-Oriented Programming
C++ fully supports object-oriented programming, including the four pillars of object-
oriented development −
Encapsulation
Data hiding
Inheritance
Polymorphism
//Anyone who has used either an Apple Macintosh or a PC running Windows has
indirectly used C++ because the primary user interfaces of these systems are written in
C++.//
C++ Program Structure
Let us look at a simple code that would print the words Hello World.
#include<iostream>
usingnamespacestd;
The C++ language defines several headers, which contain information that is either
necessary or useful to your program. For this program, the header file <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 intmain() is the main function where program execution begins.
The next line cout<< "This is my first C++ program."; causes the message "This is my
first C++ program" 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.
Semicolons
In C++, the semicolon is a statement terminator. That is, each individual statement
must be ended with a semicolon. It indicates the end of one logical entity.
C++ Identifiers
A C++ identifier is a name used to identify a variable, function, class, or any
other user-defined item.
mohdzaraabcmove_name a_123
myname50 _temp j a23b9 retVal
C++ Keywords
The following list shows the reserved words in C++. These reserved words may not
be used as constant or variable or any other identifier names.
change all upper case letter to lower in figure as keywords are always in lower case
bool else private true
Comments in C++
C++ supports single-line and multi-line comments. All characters available inside
any comment are ignored by C++ compiler.
DATATYPES
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
Valueless void
type Typical Bit Width
char 1byte
int 4bytes
float 4bytes
double 8bytes
Note=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>
usingnamespacestd;
int main(){
cout<<"Size of char : "<<sizeof(char)<<endl;
cout<<"Size of int : "<<sizeof(int)<<endl;
cout<<"Size of short int : "<<sizeof(shortint)<<endl;
cout<<"Size of long int : "<<sizeof(longint)<<endl;
cout<<"Size of float : "<<sizeof(float)<<endl;
cout<<"Size of double : "<<sizeof(double)<<endl;
return0;
}
We are also using sizeof() operator to get size of various data types.
#Several of the basic types can be modified using one or more of these type
modifiers −
signed
unsigned
short
long
A variable definition specifies a data type and contains a list of one or more
variables of that type as follows −
typevariable_list;
Here, type must be a valid C++ data type including 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 −
inti, j, k;
char c, ch;
float f, salary;
double d;
typevariable_name = value;
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. 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.
#include <iostream>
using namespace std;
// actual initialization
a = 10;
b = 20;
g = a + b;
cout<< g;
return 0;
}
C++ Constants/Literals
Constants refer to fixed values that the program may not alter and they are
called literals.
Constants are treated just like regular variables except that their values cannot be
modified after their definition
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.
Integer Literals
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies
the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for
unsigned and long, respectively. The suffix can be uppercase or lowercase and can
be in any order.
212 // Legal
215u // Legal
078 // Illegal: 8 is not an octal digit
032UU // Illegal: cannot repeat a suffix
30u // unsigned int
30l // long
30ul // unsigned long
Floating-point Literals
A floating-point literal has an integer part, a decimal point, a fractional part, and an
exponent part. You can represent floating point literals either in decimal form or
exponential form.
While representing using decimal form, you must include the decimal point, the
exponent, or both and while representing using exponential form, you must include
the integer part, the fractional part, or both. The signed exponent is introduced by e
or E.
3.14159 // Legal
314159E-5L // Legal
510E // Illegal: incomplete exponent
210f // Illegal: no decimal or exponent
.e55 // Illegal: missing integer or fraction
Boolean Literals
There are two Boolean literals and they are part of standard C++ keywords −
You should not consider the value of true equal to 1 and value of false equal to 0.
Character Literals
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'),
or a universal character (e.g., '\u02C0').
There are certain characters in C++ when they are preceded by a backslash they
will have special meaning and they are used to represent like newline (\n) or tab (\t).
Here, you have a list of some of such escape sequence codes −
\b Backspace
\n Newline
\t Horizontal tab
#include<iostream>
usingnamespacestd;
int main(){
cout<< "Hello\tWorld \n this is me\t_sam";
return0;
}
When the above code is compiled and executed, it produces the following result −
Hello World
this is me sam
String Literals
String literals are enclosed in double quotes. A string contains characters that are
similar to character literals: plain characters, escape sequences, and universal
characters.
You can break a long line into multiple lines using string literals and separate them
using whitespaces.
Here are some examples of string literals. All the three forms are identical strings.
"hello, dear"
"hello, \
dear"
C++ allows the char, int, and double data types to have modifiers preceding them.
A modifier is used to alter the meaning of the base type so that it more precisely fits
the needs of various situations.
signed
unsigned
long
short
NOTE //The modifiers signed, unsigned, long, and short can be applied to integer
base types.
NOTE// In addition, signed and unsigned can be applied to char
NOTE// long can be applied to double.
Egunsigned int y;
1
<iostream>
This file defines the cin, cout objects, which correspond to the standard input
stream, the standard output stream.
2
<iomanip>
This file declares services useful for performing formatted I/O with so-called
parameterized stream manipulators, such as setw and setprecision.
Header Files
The C++ standard library contains files containing the standard functions that
your program may use. These files are known as header files
A header file is a file with extension .h (iostream.h) or in new complier interface we write
header file as (<iostream>)
There are two types of header files: 1) the HEADER files that the programmer writes
2)theHEADER files that comes with your compiler.
<iostream>
The standard header file input and output stream (<iostream>) contains a set of
functions for handling input and output data.
The I/O stream is a sequence of following characters written for the screen display or
read from the keyboard
The standard input and output operations in C++ are normally performed by using
the I/O stream as cin for input and cout for output.
The definitions based on ‘istream’ correspond to input streams and those based
on ‘ostream’ to output streams.
(ii) cin= The predefined object cin is an instance of istream class. The
cin object is said to be attached to the standard input device, which usually is
the keyboard.
The cin is used in conjunction with the extraction operator, which is written as >>
which are two greater than signs
(iii) Extraction operator(the double greater then sign >>) is use along with
the cin operator.
The stream extraction operator >> may be used more than once in a
single statement.
cin>> name;
cin>> age;
The cout object is said to be "connected to" the standard output device, which
usually is the display screen.
The cout is used in conjunction with the stream insertion operator, which is written
as << which are two less than signs
(iii) Insertion operator (the double less the sign <<) is used along with the cout .
The general syntax of the cout is,
cout<< x << y ;
The insertion operator << may be used more than once in a single statement
<iomanip>
C++ provides a facility to control how the output is displayed on the screen.
This is done using manipulators.
The header <iomanip> is part of the Input/output library of the C++ Standard
Library.
They have a special characteristic that they are used along with insertion (<<)
operator to change the format of the data.
There are many manipulators in C++. But as of now, we will be dealing only
with the endl and setw manipulators.
But here is an exception – the endl manipulator can be used without including
the <iomanip> file.
1. endl
The endl manipulator works the same way as the ‘\n’ character in C++. That is the
endl manipulator outputs the subsequent data or text in the next line.
But the difference is that endl also flushes the output buffer when it is used in
a program.
Egcout<<"Hello roll number "<<num<<endl;
2. setw manipulator
This manipulator is used to set the width of the output in a program. It takes up an
argument ‘n’ which is the width of the field in which the output is to be displayed.
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int num1,num2;
cout<<"Enter two numbers:”<<endl;
cin>>num1>>num2;
return 0;
}
Output:- homework
There are many type quantifiers but we are discussing only const
const
Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions.
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Arithmetic Operators
The following table shows all the arithmetic operators supported by the C/C++
language. Assume variable A holds 10 and variable B holds 20 then −
== Checks if the values of two operands are equal or not. If yes, then (A == B)
the condition becomes true. is not
true.
!= Checks if the values of two operands are equal or not. If the values (A != B)
are not equal, then the condition becomes true. is true.
> Checks if the value of left operand is greater than the value of right (A > B) is
operand. If yes, then the condition becomes true. not true.
< Checks if the value of left operand is less than the value of right (A < B) is
operand. If yes, then the condition becomes true. true.
>= Checks if the value of left operand is greater than or equal to the (A >= B)
value of right operand. If yes, then the condition becomes true. is not
true.
<= Checks if the value of left operand is less than or equal to the value (A <= B)
of right operand. If yes, then the condition becomes true. is true.
Logical Operators
Following table shows all the logical operators supported by C/C++ language.
Assume variable A holds 1 and variable B holds 0, then −
The first argument is a condition that have a result of either true(1) or false(0)
If the first argument i.e is condition is evaluates to true (1), the second
argument is evaluated.
If the first operand evaluates to false (0), the third argument is evaluated.
#include<iostream>
usingnamespacestd;
x =(y <10)?30:40;
cout<<"value of x: "<< x <<endl;
return0;
}
When the above code is compiled and executed, it produces the following result −
value of x: 40
C++ shorthands
C++ offers special shorthands that simplify the coding of a certain type of
assignment statement.
1) +=
x = x + 10; can be written as x+= 10;
x + = 10 ; equivalent to x = x + 10 ;
2)-= x - = 10 ; equivalent to x = x - 10 ;
3) *= x ∗ = 3 ; equivalent to x=x∗3;
4) /= x / = 2 ; equivalent to x = x/2 ;
5) %= x % = 2 ; equivalent to x=x%2;
Group 1 precedence
Scope resolution ::
Group 2 precedence
Array subscript [ ]
Function call ( )
Postfix increment ++
Postfix decrement ––
Group 3 precedence
Prefix increment ++
Prefix decrement ––
One's complement ~
Logical not !
Operator Description Operator
Unary negation -
Unary plus +
Group 4 precedence
Multiplication *
Division /
Modulus %
Group 5 precedence
Addition +
Subtraction –
Group 6 precedence
Group 7 precedence
Group 8 precedence
Operator Description Operator
Equality ==
Inequality !=
Group 9 precedence
Group 10 precedence
Bitwise exclusive OR ^
Group 11 precedence
Group 12 precedence
Group 13 precedence
Logical OR ||
Group 14 precedence
Conditional ? :
Group 15 precedence
Assignment =
Multiplication assignment *=
Division assignment /=
Modulus assignment %=
Addition assignment +=
Operator Description Operator
Subtraction assignment –=
Type Casting
Converting an expression of a given type into another type is known as type-casting..
Implicit or automatic conversion
Important takeaways:
1. float to int causes truncation, i.e., removal of the fractional part.
Let’s take a look at an example that uses implicit and explicit conversion:
#include <iostream>
using namespace std;
int main()
{
int a;
double b=2.55;
a = b;
cout << a << endl;//implicit conversion
a = (int)b;
cout << a << endl; // explicit conversion using C style
a = int(b);
cout << a << endl; // explicit conversion using C++ style
}
The second conversion is an explicit typecast, in this case the C style explicit
typecast. it convert double to int and loss of .55.
The third conversion is also explicit typecast, in this case the C++ style explicit
typecast. it convert double to int and loss of .55.
PHASE 1: PREPROCESSING
Preprocessor directive #include is used to include header files in our program.
These header files contain certain predefined elements (functions or objects)
that we use in our programs.
Example <iostream> header file contain cout ,cin objects
After including the header files, the expanded source code (code of header
file+ code written by programmer) is used for compilation.
PHASE 2: COMPILATION
We write our programs/source codes in the language we understand. But the
computer understands only binary language.
The compiler is a program that converts our expanded source code program
into the language understood by the computer. After compilation, what we get
is an object file.
PHASE 4: EXECUTION
The executable file is a file with .exe extension.
This is the final running version of the program (in language which the
computer understands). When this file is executed, the output is produced.
Errors in C/C++ /Type of errors
1 Syntax errors: Errors that occur when you violate the rules of writing C/C++
syntax are known as syntax errors. This compiler error indicates something that
must be fixed before the code can be compiled. All these errors are detected by
compiler and thus are known as compile-time errors.
Most frequent syntax errors are:
Missing Parenthesis (})
Printing the value of variable without declaring it
Missing semicolon
// syntax error
#include<iostream>
using namespace std;
int main()
{
int i=1;
{
cout<<"hello";
i++;
}
return 0;
}
Run on IDE
Error:
In the given example, the syntax of while loop is incorrect. This causes a syntax error.
// run-time error
#include<iostream>
using namespace std;
void main()
{
int n = 9, div = 0;
// wrong logic
// number divided by 0 leads to infinity,
// so this program abnormally terminates
div = n/0;
cout<< div ;
}
Run on IDE
Error:
div = n/0;
In the given example, there is Division by zero error. This is an example of run-
time error i.e errors occurring while running the program.
3 Linker Errors: These error occurs when after compilation we link the different
object files with main’s object while trying to RUN.
These are errors generated when the executable of the program cannot be
generated.
This may be due to wrong function prototyping, incorrect header files.
One of the most common linker error is writing Main() instead of main().
// linker error
#include<iostream>
using namespace std;
void Main() // Here Main() should be main()
{
int a = 10;
cout<<a;
}
Run on IDE
Error:
int main()
{
int i = 0;
{
cout<< "hello" ;
return 0;
}
Run on IDE
hello
5 Semantic errors : This error occurs when the statements written in the
program are not meaningful to the compiler.
#include<iostream>
using namespace std;
// semantic error
void main()
{
int a, b, c;
c=5;
a + b = c; //semantic error not meaning full
}
Run on IDE
Error
a + b = c; //semantic error
UNIT IV - Programming in C++
CONDITIONAL STATEMENTS
allows you to make decision, based upon the result of a condition. These statements are
called as Decision Making Statements or Conditional Statements.
So far, we have seen that all set of statements in a C++ program gets executed sequentially
in the order in which they are written and appear. This occurs when there is no jump based
statements or repetitions of certain calculations. But a number of situations may arise where
we may have to change the order of execution of statements depending on some specific
conditions. This involves a kind of decision making from a set of calculations.
It is to be noted that C++ language assumes any non-zero or non-null value as true and if
zero or null, treated as false.
1) if statement
if statement is the most simple decision making statement. It is used to decide whether a
certain statement or block of statements will be executed or not i.e if a certain condition is
true then a block of statement is executed otherwise not.
Syntax:
if(condition)
// Statements to execute if
// condition is true
Example:
usingnamespacestd;
intmain()
inti = 10;
if(i> 15)
}
Run on IDE
Output:
I am Not in if
2) if...else statement
The if statement alone tells us that if a condition is true it will execute a block of statements
and if the condition is false it won’t. But what if we want to do something else if the condition
is false. Here comes the else statement. We can use the else statement with if statement to
execute a block of code when the condition is false.
Syntax:
if (condition)
// condition is true
else
// condition is false
}
Flowchart:
Example:
intmain()
{
inti = 20;
if(i< 15)
{
cout<<"i is smaller than 15"<<endl;
}
else
{
cout<<"i is greater than 15"<<endl;
}
cout<< “last statement ";
return0;
}
Run on IDE
Output:
i is greater than 15
last statement
The block of code following the else statement is executed as the condition present in
the if statement is false.
3) nested-if
A nested if is an if statement that is the target of another if statement. Nested if statements
means an if statement inside another if statement.
Yes, C++ allows us to nest if statements within if statements. i.e, we can place an if
statement inside another if statement.
Syntax:
if (condition1)
if (condition2)
{
Flowchart:
Example:
// C++ program to illustrate nested-if statement
intmain()
{
inti = 10;
if(i == 10)
{
// First if statement
if(i< 15)
{
cout<<"i is smaller than 15";
}
/* It is multiline comment
Nested - if statement
will only be executed if statement above
it is true */
if(i< 12)
{
cout<<"i is smaller than 12 too";
}
else
{
cout<<"i is greater than 15";
}
}
return0;
}
Run on IDE
Output:
i is smaller than 15
Syntax
The syntax for a switch statement in C++ is as follows –
switch (condition)
break;
break;
switch (n)
break;
break;
Choice is 2
int main()
{
char op;
int num1, num2;
switch(op)
{
case'+':cout<< num1+num2;
break;
case'-':cout<< num1-num2;
break;
case'*':cout<< num1*num2;
break;
case'/':cout<< num1/num2;
break;
return0;
}
Output
3- 8= -5
C++ Loop
There may be a situation, when you need to execute a block of code several
number of times.
For example: Suppose we want to print “Hello World” 10 times. This can be
done in two ways as shown below:
Iterative Method
Iterative method to do this is to write the printf() statement 10 times.
// C++ program to illustrate need of loops
#include <iostream>
usingnamespacestd;
intmain()
{
cout<< "Hello World\n";
cout<< "Hello World\n";
cout<< "Hello World\n";
cout<< "Hello World\n";
cout<< "Hello World\n";
cout<< "Hello World\n";
cout<< "Hello World\n";
cout<< "Hello World\n";
cout<< "Hello World\n";
cout<< "Hello World\n";
return0;
}
for Loop
Syntax:
for (initialization expr; test expr; update expr)
{
// body of the loop
// statements we want to execute
}
intmain()
{
for(inti = 1; i<= 5; i++)
{
cout<< "Hello World\n";
}
return0;
}
While Loop
While loops are used in situations where we do not know the exact
number of iterations of loop beforehand. The loop execution is
terminated on the basis of test condition.
Syntax:
initialization expression;
while (test_expression)
{
// statements
update_expression;
}
intmain()
{
inti = 1;// initialization expression
{
cout<< "Hello World\n";
return0;
}
Run on IDE
Output:
Hello World
Hello World
Hello World
Hello World
Hello World
do while loop
The main difference between do while loop and while loop is that indo while
loop the condition is tested at the end of loop body
Note: In do while loop the loop body will execute at least once irrespective of
test condition.
Syntax:
initialization expression;
do
{
// statements
update_expression;
}
while (test_expression);
intmain()
{
inti = 1; // Initialization expression
do
{
// loop body
cout<< "Hello World\n";
}
while(i< =5); // test expression
return0;
}
Part II Functions
A function is a group of statements that together perform a task. Every C++
program has at least one function, which is main()
A function is a set of statements that take inputs, do some specific computation and
produces output.
Note=//The idea is to put some commonly or repeatedly done task together and
make a function, so that instead of writing the same code again and again for
different inputs, we can call the function.
FunctionDeclaration
Function declaration tells compiler about number of parameters function takes, data-
types of parameters and return type of function.
example
intmain()
{
inta = 10, b = 20; //10,20 are actual parameters
cout<<"m is %d", m;
return0;
}
intmax(intx, inty) //we are defining a function name max
{
if(x > y) // x and y are formal parameters
returnx;
else
returny;
}
Run on IDE
Output:
m is 20
#include<iostream>
using namespace std;
// A function with default arguments, it can be called with
//2 arguments or 3 arguments or 4 arguments and return a integer value
int sum(int x, int y, int z=10, int w=10)
{
result=x+y+z+w;
return (result);
}
int main()
{
cout<< sum(10, 15) <<endl;
/*we can write this single line statement in two lines 1) a= sum(10,15);
2) cout<<a<<endl; */
cout<< sum(10, 15, 25) <<endl;
cout<< sum(10, 15, 25, 30) <<endl;
return 0;
}
Output:Copy
45
60
80
Note=Once default value is used for an argument, all subsequent arguments must
have default value.
//Invalid or give error because z has default value, but w after it
// doesn't have default value
intsum(intx, inty, intz=10, intw)
Const Keyword
Constant is something that doesn't change.
In C and C++ we use the keyword const to make program elements constant.
Const keyword can be used in many context in a C++ program. Const keyword can be
used with:
1. Variables
2. Function arguments
3. Objects
1) Constant Variables
If you make any variable as constant, using const keyword, you cannot change its value.
Also, the constant variables must be initialized while declared.
int main
{
constinti = 10;
i++; // This leads to Compile time error
}
In this program we have made i as constant, hence if we try to change its value, compile
time error is given.
2) Const Function Arguments
We can make the arguments of a function as const. Then we cannot change any of
them.
void demo(constinti) //we have function with name demo
//and one constant argument name i
{
i++; // Error
}
Parameter Passing to functions
The parameters passed to function are called actual parameters. For example,
in the above program 10 and 20 are actual parameters.
array initialization,
char greeting[6] = "Hello";
or
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
Actually, you do not place the null character at the end of a string
constant. The C++ compiler automatically places the '\0' at the end of
the string when it initializes the array.
#include <iostream>
using namespace std;
int main () {
return 0;
When the above code is compiled and executed, it produces the following
result −
Greeting message: Hello
1
strcpy(s1, s2);
2 strcat(s1, s2);
3
strlen(s1);
4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0
if s1>s2.
#include <iostream>
#include <cstring>
int main () {
char str3[10];
int len ;
cout << "strcpy( str3, str1) : " << str3 << endl;
cout << "strcat( str1, str2): " << str1 << endl;
len = strlen(str1);
#include <iostream>
#include <string> //to use string class we include <string> header file in program
int main () {
string str3;
int len ;
str3 = str1;
len = str3.size();
return 0;
int main()
{
char s1[20];
char s2[20];
int i;
cout<<"enter the string"<<endl;
cin>>s1;
for(i=0;s1[i]!=0;i++)
{
if(s1[i]>='a' && s1[i]<='z')
s2[i]=s1[i]-32;
else
s2[i]=s1[i]+32;
}
cout<<”string after case conversion = ”<<s2;
return 0;
}
OUTPUT
enter the string
compuTER
string after case conversion = COMPUter