0% found this document useful (0 votes)
91 views65 pages

Unit III COMPUTER

The document provides an introduction to C++, including: - C++ is a middle-level language that combines high-level and low-level features. It was developed in 1979 as an enhancement to C. - C++ fully supports object-oriented programming concepts like encapsulation, inheritance, and polymorphism. Popular C++ compilers include Microsoft Visual C++. - Key elements of a basic C++ program are included, such as main functions, headers, comments, data types, variables, and literals.

Uploaded by

Abhishek Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
91 views65 pages

Unit III COMPUTER

The document provides an introduction to C++, including: - C++ is a middle-level language that combines high-level and low-level features. It was developed in 1979 as an enhancement to C. - C++ fully supports object-oriented programming concepts like encapsulation, inheritance, and polymorphism. Popular C++ compilers include Microsoft Visual C++. - Key elements of a basic C++ program are included, such as main functions, headers, comments, data types, variables, and literals.

Uploaded by

Abhishek Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

UNIT III – Introduction to C++

C++ is regarded as a middle-level language, as it comprises a combination of both


high-level and low-level language features.

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;

// main() is where program execution begins.


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

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

a) An identifier starts with a letter A to Z or a to z or an underscore (_) followed by


zero or more letters, underscores, and digits (0 to 9).

b) C++ does not allow punctuation characters such as @, $, and % within


identifiers.

c) C++ is a case-sensitive programming language. Thus, Manpower


and manpower are two different identifiers in C++.

Here are some examples of valid identifiers names−

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

break export protected try

case extern public typedef

Catch false register typeid

Char float typename

Class for return union

Const friend short unsigned

goto signed using

Continue if sizeof virtual

Default inline static void

Delete int static_cast volatile

Do long struct char

Double namespace switch while

Comments in C++
C++ supports single-line and multi-line comments. All characters available inside
any comment are ignored by C++ compiler.

C++ comments start with /* and end with */.


A comment can also start with //, extending to the end of the line.

DATA TYPES &VARIABLES

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.

Primitive or Built-in DataTypes


C++ offers the programmer a 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
type Typical Bit Width

char 1byte

int 4bytes

short int 2bytes

long 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

DATATYPE SIZE RANGE

Char 1byte -127 to 127 or 0 to 255

unsigned char 1byte 0 to 255

signed char 1byte -127 to 127

Int 4bytes -2147483648 to 2147483647

unsigned int 4bytes 0 to 4294967295

signed int 4bytes -2147483648 to 2147483647


VARIABLES
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++ is case-sensitive

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 −

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;

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 −

typevariable_name = value;

Some examples are −

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


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

Variable Scope in C++


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

 Inside a function or a block which is called local variables,

 In the definition of function parameters which is called formal parameters.


 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. 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;

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

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.

Here are some examples of integer literals −

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.

Here are some examples of floating-point literals −

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 −

 A value of true representing true.

 A value of false representing false.

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 −

Escape sequence Meaning

\b Backspace
\n Newline

\t Horizontal tab

Following is the example to show a few escape sequence characters −

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

"hello, " "d" "ear"


C++ Modifier Types

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.

The data type modifiers are listed here −

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

C++ Basic Input/Output


C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a device
like a keyboardto main memory(CPU), this is called input operation and if bytes flow
from main memory(CPU) to a device like a display screenthis is called output
operation.

I/O Library Header Files


There are following header files important to C++ programs −

Sr.No Header File & Function and Description

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 ‘ios’ correspond to input and output streams (hence io).

The definitions based on ‘istream’ correspond to input streams and those based
on ‘ostream’ to output streams.

C++ allows three types of stream classes, namely,


iostream
istream
ostream
1) iostream = The iostream supports both input/output stream of functions to
read a stream of characters form the keyboard and to display a stream of
objects onto the video screen.

2) (i) istream = The istream consists of input functions to read a streams of


characters from the keyboard.

(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 general syntax of the cin is


cin>> variable 1 >> variable 2 >> …variable n;
cin>> a >> b ;

The stream extraction operator >> may be used more than once in a
single statement.

cin>> name >> age;

This will be equivalent to the following two statements −

cin>> name;
cin>> age;

3) (i) ostream = The ostream consists of output functions to write a


character onto the screen.

(ii) cout= The predefined object cout is an instance of ostream class.

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<< variable 1 << variable 2 <<.....<< variable n;

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.

It defines the manipulator functions


like resetiosflags(), setiosflags(), setbase(), setfill(), setprecision(), and setw().

Let us understand what manipulators are.


 Manipulators are functions that are used to format or modify the output
stream in various ways.

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

 To be able to use manipulators in our program, we must include <iomanip>


header file in our source program.

 But here is an exception – the endl manipulator can be used without including
the <iomanip> file.

Now let us see how these two manipulators work.

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.

By default, the output in the field is right-aligned

#include<iostream>
#include<iomanip>
using namespace std;

int main()
{
int num1,num2;
cout<<"Enter two numbers:”<<endl;
cin>>num1>>num2;

cout<<"Displaying the two numbers"<<endl;


<<"Num1:"<<setw(8)<<num1<<endl
<<"Num2:"<<setw(8)<<num2<<endl;

return 0;
}

Output:- homework

Type Qualifiers in C++

Defination-The type qualifiers provide additional information about the variables


they precede.

There are many type quantifiers but we are discussing only const

const

Objects or variable of type const cannot be changed by your program during


execution.

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 −

Operator Description Example

+ Adds two operands. A + B = 30

− Subtracts second operand from the first. A − B = -10

* Multiplies both operands. A * B = 200

/ Divides numerator by de-numerator. B/A=2

% Modulus Operator and remainder of after an integer division. B%A=0

++ Increment operator increases the integer value by one. A++ = 11

-- Decrement operator decreases the integer value by one. A-- = 9


Relational Operators
The following table shows all the relational operators supported by C/C++. Assume
variable A holds 10 and variable B holds 20 then −

Operator Description Example

== 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 −

Operator Description Example


&& Called Logical AND operator. If both the operands are non-zero, then (A && B)
the condition becomes true. is false.

|| Called Logical OR Operator. If any of the two operands is non-zero, (A || B) is


then the condition becomes true. true.

! Called Logical NOT Operator. It is used to reverse the logical state of !A


its operand. If a condition is true, then Logical NOT operator will
make it false.

Conditional operator or ternary operator


Condition ?X : Y

expression ?expression : expression


The conditional operator (? :) is a ternary operator because it is a operator that
takes three arguments.

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

int main (){


// Local variable declaration:
int x ;
inty =20;

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 ;

The operator += tells the compiler to assign to a the value of a+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;

C++ Operator Precedence


In order to properly evaluate an expression such as 4 + 2 * 3, we must
understand both what the operators do, and the correct order to apply them.
The order in which operators are evaluated in a compound expression is
called operator precedence.
Using normal mathematical precedence rules (which state that multiplication is
resolved before addition), we know that the above expression should evaluate
as 4 + (2 * 3) to produce the value 10.
In C++, when the compiler encounters an expression, it must similarly analyze
the expression and determine how it should be evaluated.
To assist with this, all operators are assigned a level of precedence. Those with
the highest precedence are evaluated first. You can see in the table below that
multiplication and division have a higher precedence than addition and
subtraction.
The compiler uses these levels to determine how to evaluate expressions it
encounters.
If two operators with the same precedence level are adjacent to each other in
an expression, the operator associativity rules are used . Operator associativity
beyond syllabus
Operator precedence specifies the order of operations in expressions that
contain more than one operator.
Precedence level 1 is the highest precedence level, and level 15 is the lowest.
Operators with a higher precedence level get evaluated first

Operator Description Operator

Group 1 precedence

Scope resolution ::

Group 2 precedence

Member selection (object or pointer) . or –>

Array subscript [ ]

Function call ( )

Postfix increment ++

Postfix decrement ––

Group 3 precedence

Size of object or type sizeof

Prefix increment ++

Prefix decrement ––

One's complement ~

Logical not !
Operator Description Operator

Unary negation -

Unary plus +

Create object new

Destroy object delete

Group 4 precedence

Multiplication *

Division /

Modulus %

Group 5 precedence

Addition +

Subtraction –

Group 6 precedence

Left shift <<

Right shift >>

Group 7 precedence

Less than <

Greater than >

Less than or equal to <=

Greater than or equal to >=

Group 8 precedence
Operator Description Operator

Equality ==

Inequality !=

Group 9 precedence

Bitwise AND &

Group 10 precedence

Bitwise exclusive OR ^

Group 11 precedence

Bitwise inclusive OR &#124;

Group 12 precedence

Logical AND &&

Group 13 precedence

Logical OR &#124;&#124;

Group 14 precedence

Conditional ? :

Group 15 precedence

Assignment =

Multiplication assignment *=

Division assignment /=

Modulus assignment %=

Addition assignment +=
Operator Description Operator

Subtraction assignment –=

Left-shift assignment <<=

Right-shift assignment >>=

Type Casting
Converting an expression of a given type into another type is known as type-casting..
Implicit or automatic conversion

Almost every compiler makes use of what is called automatic typecasting. It


automatically converts one type into another type.

Important takeaways:
1. float to int causes truncation, i.e., removal of the fractional part.

2. double to float causes rounding of digit.

3. long to int causes dropping of excess higher order bits.

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
}

Note: the output of all cout statements is 2.

The first conversion is an implicit conversion (the compiler decides.) As the


compiler should give a warning it convert double to int and loss of .55.

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.

Compilation, Linking & Execution of a C++ program:

SOURCE CODE -code written by programmer Eg file main.cpp written in c++

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.

Object file with extension .obj or .o


PHASE 3: LINKING
Important step is to link to standard library files. The object file is linked with
library files.

Library files contain definitions(complete working code) of library functions and


objects .

The output of the linking phase is an executable 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

// C++ program to illustrate


// syntax error
#include<iostream>
using namespace std;
void main()
{
int x = 10;
int y = 15;

cout<<x<<y // semicolon missed


}
Run on IDE
Error:
error: expected ';' before '}' token

Syntax of a basic construct is written wrong. For example : while loop

// syntax error
#include<iostream>
using namespace std;

int main()
{

int i=1;

while(.) //error while() cannot contain "." as an argument.


//condition expression missing

{
cout<<"hello";
i++;
}
return 0;
}

Run on IDE
Error:

error: expected expression before '.' token


while(.)

In the given example, the syntax of while loop is incorrect. This causes a syntax error.

2 Run-time Errors : Errors which occur during program execution(run-time) after


successful compilation are called run-time errors.
One of the most common run-time error is division by zero also known as Division error.
These types of error are hard to find as the compiler doesn’t point to the line at which the
error occurs.
For more understanding run the example given below.

// 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:

warning: division by zero [-Wdiv-by-zero]

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:

(.text+0x20): undefined reference to `main'


4 Logical Errors : On compilation and execution of a program, desired output is
not obtained when certain input values are given.
These types of errors which provide incorrect output but appears to be error
free are called logical errors.
These are one of the most common errors done by beginners of programming.
These errors solely depend on the logical thinking of the programmer and are
easy to detect if we follow the line of execution and determine why the
program takes that path of execution.

// C++ program to illustrate


// logical error
#include<iostream>
using namespace std;

int main()
{
int i = 0;

for(i = 0; i < 3; i++); // logical error ; a semicolon after loop

{
cout<< "hello" ;

return 0;
}
Run on IDE
hello

expected output = hellohellohello

no error shown but output obtained is incorrect

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

error: lvalue required as left operand of assignment

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.

C++ programming language provides following types of conditional or decision making


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:

C++ program to illustrate If statement


#include<iostream>

usingnamespacestd;

intmain()

inti = 10;

if(i> 15)

cout<<"10 is less than 15";

cout<<"I am Not in if";

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

// Executes this block if

// condition is true

else

// Executes this block if

// condition is false

}
Flowchart:

Example:

// C++ program to illustrate if-else statement


#include<iostream>
usingnamespacestd;

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)

// Executes when condition1 is true

if (condition2)
{

// Executes when condition2 is true

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

i is smaller than 12 too


C++ switch statement
A switch statement allows a variable to be tested for equality against a list
of values. Each value is called a case, and the variable being switched on is
checked for each case.

Syntax
The syntax for a switch statement in C++ is as follows –

switch (condition)

case 1: // code to be executed if condition=some value a ;

break;

case 2: // code to be executed if condition= some value b;

break;

default: // code to be executed if condition doesn't match any cases

Understanding the syntax with help of variable n

switch (n)

case 1: // code to be executed if n = 1;

break;

case 2: // code to be executed if n = 2;

break;

default: // code to be executed if n doesn't match any cases

Important Points about Switch Case Statements:


1. The expression provided in the switch should result in a constant
value otherwise it would not be valid.
Valid expressions for switch:
2. // Constant expressions allowed
3. switch(1+2+23)

Invalid switch expressions for switch:


// Variable expression not allowed
switch(ab+cd)
switch(a+b+c)

4. Duplicate case values are not allowed.

5. The default statement is optional. Even if the switch case statement do


not have a default statement, it would run without any problem.
6 The break statement is used inside the switch to terminate a
statement sequence. When a break statement is reached, the
switch terminates, and the flow of control jumps to the next line
following the switch statement.
7 The break statement is optional. If omitted, execution will
continue on into the next case. The flow of control will fall through
to subsequent cases until a break is reached.
Example:
// Following is a simple program to demonstrate
// syntax of switch.
#include <iostream.h>
intmain()
{
intx = 2;
switch(x)
{
case1: cout<<"Choice is 1";
break;
case2: cout<<"Choice is 2";
break;
case3: cout<<"Choice is 3";
break;
default: cout<<"Choice is neither 1,2,3";
break;
}
return0;
}
Run on IDE
Output:

Choice is 2

Example: Simple Calculator using switch


statement
# include <iostream>
usingnamespacestd;

int main()
{
char op;
int num1, num2;

cout<<"Enter operator either + or - or * or /: ";


cin>> op;

cout<<"Enter two operands: ";


cin>> num1 >> num2;

switch(op)
{
case'+':cout<< num1+num2;
break;

case'-':cout<< num1-num2;
break;

case'*':cout<< num1*num2;
break;

case'/':cout<< num1/num2;
break;

default:cout<<"Error! operator is not correct";

// If the operator is other than +, -, * or /, error message is shown

return0;
}

Output

Enter operator either + or - or * or divide : -

Enter two operands:


3

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

2nd method Using Loops


In Loop, the statement needs to be written only once and the loop
will be executed 10 times as shown below.

Three type of loop


1. For loop
2. While loop
3. Do while loop
In computer programming, a loop is a sequence of instructions that
is repeated until a certain condition is reached.
In loop we have three parts:
1) Initialization
2) Testing
3) Updation

for Loop

A for loop is a repetition control structure which allows us to write a


loop that is executed a specific number of times.

Syntax:
for (initialization expr; test expr; update expr)
{
// body of the loop
// statements we want to execute
}

Initialization=First initialize this loop variable to some value


Testing =Test whether this variable is less than or greater than given
value.
Execution of loop =If statement is true, then loop body is executed
and
Updating =Loop variable gets updated.

// C++ program to illustrate for loop


#include <iostream>
usingnamespacestd;

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

// C++ program to illustrate for loop


#include <iostream>
usingnamespacestd;

intmain()
{
inti = 1;// initialization expression

while(i< =5) // test expression

{
cout<< "Hello World\n";

i++;// update expression


}

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

Note: Notice the semi – colon(“;”) in the end of loop.

// C++ program to illustrate do-while loop


#include <iostream>
usingnamespacestd;

intmain()
{
inti = 1; // Initialization expression

do
{
// loop body
cout<< "Hello World\n";

i++;// update expression

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

The general form of a C++ function definition is as follows −


return_typefunction_name( parameter list ) {
body of the function
}

FunctionDeclaration

Function declaration tells compiler about number of parameters function takes, data-
types of parameters and return type of function.

A function declaration has the following parts −


return_typefunction_name( parameter list );

example

int max(int, int);

Note=Putting parameter names in function declaration is optional in function declaration,


but it is necessary to put them in definition

// An example function that takes two parameters 'x' and 'y'


// as input and returns max of two input numbers

// main function which returns integer.


#include <iostream>

intmax(int, int); //function declaration

intmain()

{
inta = 10, b = 20; //10,20 are actual parameters

intm = max(a, b);//Calling fxnmax to find maximum of 'a' and 'b'

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

Default Arguments in C++

A default argument is a value provided in function declaration that is


automatically assigned by the compiler if caller of the function doesn’t provide
a value for the argument with default value.

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

The parameters received by function are called formal parameters. For


example, in the above program x and y are formal parameters.

There are two most popular ways to pass parameters.

Call by Value: In this parameter passing method, values of actual parameters


are copied to function’s formal parameters and the two types of parameters
are stored in different memory locations. So any changes made inside functions
are not reflected in actual parameters of caller.
Call by Reference Both actual and formal parameters refer to same locations,
so any changes made inside the function are actually reflected in actual
parameters of caller.
Program for above discussed in class.

PART III C++ Strings

++ provides following two types of string representations −

 The C-style character string.


 The string class type introduced with Standard C++.

1 The C-Style Character String


The C-style character string originated within the C language and
continues to be supported within C++.

String is actually a one-dimensional array of characters which is


terminated by a null character '\0'.

Thus a null-terminated string contains the characters that comprise the


string followed by a null.

The following declaration and initialization create a string consisting of


the word "Hello". To hold the null character at the end of the array, the
size of the character array containing the string is one more than the
number of characters in the word "Hello."

array initialization,
char greeting[6] = "Hello";

or
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

Following is the memory presentation of above defined string in C/C++ −

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.

Let us try to print above-mentioned string −


Live Demo

#include <iostream>
using namespace std;

int main () {

char greeting[6] = "Hello";

cout << "Greeting message: ";

cout << greeting << endl;

return 0;

When the above code is compiled and executed, it produces the following
result −
Greeting message: Hello

C++ supports a wide range of functions that manipulate null-terminated


strings −

Sr.No Function & Purpose

1
strcpy(s1, s2);

Copies string s2 into string s1.

2 strcat(s1, s2);

Concatenates string s2 onto the end of string s1.

3
strlen(s1);

Returns the length of string 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.

Following example makes use of few of the above-mentioned functions −


Live Demo

#include <iostream>

#include <cstring>

using namespace std;

int main () {

char str1[10] = "Hello";

char str2[10] = "World";

char str3[10];

int len ;

// copy str1 into str3

strcpy( str3, str1);

cout << "strcpy( str3, str1) : " << str3 << endl;

// concatenates str1 and str2

strcat( str1, str2);

cout << "strcat( str1, str2): " << str1 << endl;

// total lenghth of str1 after concatenation

len = strlen(str1);

cout << "strlen(str1) : " << len << endl;


return 0;

When the above code is compiled and executed, it produces result


something as follows −
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10

2 The String Class in C++


The standard C++ library provides a string class type that supports all
the operations mentioned above, additionally much more functionality.
Let us check the following example −
Live Demo

#include <iostream>

#include <string> //to use string class we include <string> header file in program

using namespace std;

int main () {

string str1 = "Hello";

string str2 = "World";

string str3;

int len ;

// copy str1 into str3 use = operator

str3 = str1;

cout << "str3 : " << str3 << endl;


// concatenates str1 and str2 use + operator

str3 = str1 + str2;

cout << "str1 + str2 : " << str3 << endl;

// total length of str3 after concatenation use size() function

len = str3.size();

cout << "str3.size() : " << len << endl;

return 0;

When the above code is compiled and executed, it produces result


something as follows −
str3 : Hello
str1 + str2 : HelloWorld
str3.size() : 10

WAP FOR CASE CONVERSION OF INPUT STRING


#include <iostream>
#include<string>
using namespace std;

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

WAP FOR REVERSING THE STRING


Discussed in class.

Part IV STRUCTURES: DISCUSSED IN CLASS:

You might also like