0% found this document useful (0 votes)
5 views

C++M-I(4,5,6)

The document provides an overview of C++ programming, covering its definition, advantages, applications, and compilers. It details fundamental concepts such as tokens, comments, input/output commands, and data types, including built-in, derived, and user-defined types. Additionally, it explains variable declaration, initialization, and the use of pointers, functions, arrays, and references in C++.

Uploaded by

My pat
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)
5 views

C++M-I(4,5,6)

The document provides an overview of C++ programming, covering its definition, advantages, applications, and compilers. It details fundamental concepts such as tokens, comments, input/output commands, and data types, including built-in, derived, and user-defined types. Additionally, it explains variable declaration, initialization, and the use of pointers, functions, arrays, and references in C++.

Uploaded by

My pat
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/ 13

CSE/C++/Module-I/Trilochan Rout/Lecture: 4, 5, 6 1

IIIT, Bhubaneswar
Dept. Comp. Sc. & Engg.
C++ and Object Oriented Programming
Lecture: 4, 5, 6

Getting started with C++


I. What is C++? II. Advantages of C++ III. Applications of C++ IV. Compilers for Programming with
C++V. Comment lines in C++ VI. Input & Output Commands VII. C++ Tokens VIII. Storage class
IX. Data types in C++
Lecture: 4
I. What is C++?
• C++ is an object oriented programming language.
• C++ supports C’s notion and provides a better programming feature than that of C
programming.
• It supports data abstraction.
• It supports generic programming.
• It was developed by Bjarne Stroustrup at AT& T Bell laboratory in the year of 1980.
• He added the class concept to existing C language, that’s why it is known as C with classes.
• It was renamed to C++ in 1983.
II. Advantages of C++
• As hierarchy related objects can be created using C++, special object oriented libraries can
be build to be used later by many programs.
• C++ programs are easily maintainable and expandable when a new feature needs to be
implemented; it is very easy to add to the existing structure of an object.
• C++ is versatile language for handling very large programs.
• C++is ahigh-level language: whenyouwriteaprograminit,theshorthand’saresufficiently
expressivethatyoudon’t needto worry aboutthedetails ofprocessorinstructions. C++does
giveaccesstosomelower-levelfunctionality thanotherlanguages(e.g. memory addresses).
III. Applications of C++
• It is suitable for any programming task including development of editors, compilers, data
bases, communication systems and complex real life application systems.
• It is used for developing different application that involves local and wide area networking
and graphics user interaction and database access.
• It is widely used for teaching and research purpose.
• Used in developing and implementation of long distance telephone systems and a
numerous computational application.
CSE/C++/Module-I/Trilochan Rout/Lecture: 4, 5, 6 2

IV. Compilers for Programming with C++


• For execution of programs written in C++, various types of compilers are available.
• The compiler will convert the user code (program statements) into object code (machine
language format) for execution various action.
• A large number of C++ compilers develop by different organizations. Some of the
compilers are:
1. Turbo C++ compiler
2. Borland C++
3. Dev C++
4. Microsoft visual C++
5. LCC-Win 32
6. GCC (for multiple platform)
V. Comment lines in C++:
/*
This is a simple C++ program.
Call this file Sample.cpp.
*/
• This is a comment. The contents of a comment are ignored by the compiler.
• The purpose of a comment is to describe or explain the operation of a program to anyone
reading its source code. In the case of this comment, it identifies the program. In more
complex programs, you will use comments to help explain what each feature of the
program is for and how it goes about doing its work.
• In other words, you can use comments to provide a “play-by-play” description of what
your program does.
• In C++, there are two types of comments. The one you’ve just seen is called a multiline
comment. This type of comment begins with a /* (a slash followed by an asterisk). It ends
only when a */ is encountered. Anything between these two comment symbols is
completely ignored by the compiler.
• Multiline comments may be one or more lines long. The second type of comment (single-
line).
// A C++ program begins at main().
• This is the second type of comment available in C++: the single-line comment. Single-
linecomments begin with // and stop at the end of the line.
• Typically, C++ programmers use multilinecomments when writing larger, more detailed
commentaries and single-line comments when shortremarks are needed.
VI. Input & Output Commands:
• C++ supports all input / output function of C.
• C++ supports a number of input / output (I/O) operation to read and write operations.
• The input and output commands of C++ are defined in the header file <iostream.h>.
• C function can be implemented in C++ programs by using <stdio.h> header file.
CSE/C++/Module-I/Trilochan Rout/Lecture: 4, 5, 6 3

• The header file of C++ can be define in following ways:


Syntax:
#include<iostream.h>
Or # include “iostream.h“
Or # include <iostream> //[ For ANSI C++ Compiler]
• The header file <iostream.h> consists of 2 parts
o istream.h → input stream header file
o ostream.h → output stream header file
Note:

❖ Stream is a flow of data in bytes in sequence.


❖ It is an intermediate between I/O device and the user.
❖ If data is received from input devices in sequence then it is called Source Stream.
❖ When the data is passed to the output device then it is called as Destination Stream.
The Basic Input Object used in C++:
• cin → it is the standard input object and works exactly same as that scanf( ) in C
programming.
o Syntax: cin>>variable_name;(each statement must have end with semicolon)
Example: int x;
cin>> x; //”>>” → this is known as extraction operator
• Multiple variable can be declared using the following
o Syntax: cin>> var1 >> var2 >> var3 >> . . . . . >>varn;
Example: int x, y, z;
cin>> x >> y >> z;
• cout → (standard output object) works exactly same as that printf ( ) in C programming.
o Syntax: cout<<variable_name or string;
Example:
int x;
cout<< “Enter value for x”;
cin>> x ;
cout<< “Entered value of x is: “ << x;
• Multiple variable can be declared using the following syntax:
▪ cout<< variable1 << variable2 << . . . . . <<variable;
Note:
• In C++, the operator<< (insertion operator) is overloaded for cout statements in ostream
class and the operator >> (extraction operator) is overloaded for cinstatements in istream
class.
• Input / output statements can be declared in multiple lines but a semicolon must have to
be given at the end of the input / output statement.
CSE/C++/Module-I/Trilochan Rout/Lecture: 4, 5, 6 4

Lecture: 5
VII. C++ Tokens:
• The smallest individual units in a program or the smallest meaningful symbols in the
language are known as tokens.
• Each statement in a program consists of different components which independently
identified as tokens by the compiler.
• Tokens can be classified into the following types:

Token type Description/Purpose Examples

Words withspecial
Keywords int, double, for, auto
meaningto the compiler

Names of things that are


Identifiers cout, std, x, myFunction
not built into the language

Basic constant values


Literals whose value is specified "Hello, world!", 24.3, 0, ’c’
directly in the source code

Mathematical or logical
Operators +, -, &&, %, <<
operations

Punctuation defining the


Punctuation/Separators {}(),;
structure of a program

Spaces of various sorts; Spaces, tabs, newlines,


Whitespace
ignored by the compiler comments

Value will remain


Constants unchanged during const, enum
execution

Example:

Int x = 10 ;

keyword identifier operator constant special character


CSE/C++/Module-I/Trilochan Rout/Lecture: 4, 5, 6 5

Keywords:
• Keywords are reserved set of words with fixed meanings.
• These keywords cannot be used as variables names or other user defined program
elements.
• There are 48 keywords in C++ (including the 32 keyword of C).
• In addition the existing 32 keywords of C, there are keywords specific to C++ and 15 other
keywords added by ANSI Committee.
o C & C++ common keywords

asm double new switch

auto else operator template

break enum private this

case extern protected throw

catch float public try

char for register typedef

class friend return union

const goto short unsigned

continue if signed virtual

default inline sizedof void

delete int static volatile

do long struct while

Identifiers:
• Identifiers are name given to various program elements, such as variables, function,
arrays, structure, pointer, etc.
• They are user defined names, consisting of a sequence of alphabetic character, digits and
underscore( _ ).
• The first letter must be start with a character or underscore.
• Uppercase and lowercase letters are distinct.
• ANSI C++ has no bound on the length of identifier.
• Keywords can’t be used as identifier name.
CSE/C++/Module-I/Trilochan Rout/Lecture: 4, 5, 6 6

Example:
int a, b;
- The above example represent that int is the keyword and a, b are two integer
identifiers.
Variable Declaration and Initialization:
• A variable is a name given to memory location.
• It can also be stated as an identifiers that holds varying values.
• The syntax for variable declaration remains same as that of C programming:
1. <data type><variable name>;
• The major difference in C++ is that, we can declare the variables anywhere in the program
unlike C where declaration is done at the beginning.
• C++ syntax for initialization is:
1. <data type><variable name> = value;
• Initialization can done by using “cin” statement
1. cin>> x;
• Again initialization can be done by dynamic initialization (that is declaration &
initialization in one statement)
1. int num = 20;
2. float avg = num / 4 ;
CSE/C++/Module-I/Trilochan Rout/Lecture: 4, 5, 6 7

Lecture: 6
IX. Data Types in C++:
• Data are the raw documents or files which are used in computers.
• C++ supports all the C datatypes.
o Generally data can be four types:
1. Integer
2. Character
3. String
4. Floating point types
• Data type represents the characteristics of data which type the data is?
• C++ data types can be classified into the following types
o Derived data type
o Basic or Built-in or Fundamental data type
o User-defined data type

C++ Data types

User-defined Built-in/ Derived


predefined data type

Void Floating type


Integral type

int char float double

Built in data type or predefined or primitive or fundamental data type


• Basic or Built-in datatype:
- The built-in datatypes are also known as basic or fundamental datatypes. The basic
datatypes may have several modifiers. The modifiers signed, unsigned, long and
short may be applied to character and integer basic datatypes. The modifier long
may also be applied to double.
- Two normal uses of void are:
1. to specify the return type of a function when it is not returning any value.
2. to indicate an empty argument list to a function.
e.g void function(void);
Another use of void is in the declaration of the generic pointers.
void *gp; //gp becomes a generic pointer
A generic pointer can be assigned a pointer value of any basic datatype, but it
cannot be dereferenced.
int *ip;
void *gp;
gp=ip; //assign int pointer to void pointer
ip=gp; //not correct until specifically typecasted
ip=(int*)gp; //correct
CSE/C++/Module-I/Trilochan Rout/Lecture: 4, 5, 6 8

• Derived data type:


- The derived data types which are used in C++ programming are:
o Pointer
o Function
o Arrays
o References: it is alias that is alternative name of a previously defined variable
o
➢ Pointer:
- A pointer is a memory variable that stores the memory address of another variable
of same data type.
- It is declared like another variable and is denoted by ‘*’ operator. ‘*’ means value at
address operator.
- It is also known as dereference operator.
▪ Syntax:
<data type> *<ptr name>;
Example:

int *x ; // declaration of pointer variable, it can accept address of


another variable

*x; // value at this address

char *ch ;
float *f ;
- In the first statement ‘x’ is an integer pointer and which holds the address of any
integer variable only. Similarly in the second statement ‘ch’ is a character pointer
that can stores the address of any character variable and ‘f’ is float pointer that can
store the address of any float variable only.
Example:
#include<iostream.h>
#include<conio.h>
void main( )
{
int x = 2;
int *p;
cout<<”\n Address of X = “<<&x;
p = &x; //p contains the address of integer variable of x
cout<<”\n Value of X = “<< *p;
getch( );
}

Output:

Explanation:
- In this program x is an integer variable and *p is an integer pointer.
- The first coutstatement displays the address of variable.
CSE/C++/Module-I/Trilochan Rout/Lecture: 4, 5, 6 9

- Then address of variable x is assigned to pointer p.


- The pointer variable is always used to store address of another variable.
- The second cout statement displays the value of x using pointer p.

Variable x Address of 4096 2


variable x

P=&x
Pointer variable p

➢ Function:
- A function is a self contained block or a sub-program of one or more statements that
perform a special task when called.
- We can use a single function for multiple times or with multiple definitions called as
function overloading.
- It means reusability of program code.
Example:
main ( ) fun A ( )
{
..... {
.....
fun A( ); .....
.....
return;
..... funB ( )
fun B( ); }
..... {
..... .....
}
return;
➢ Arrays:
}
- It is a collection of similar data types which are stored in separate contiguous
memory locations.
Example:
intarr[5]; →the statement declares an array arr[ ] which can hold 5 integer values,
which are stored in contiguous memory location.

- Each of the elements in the array located in separated memory locations


sequentially.
arr[0] arr[1] arr[2] arr[3] arr[4]

- The array numbering starts from 0 to n-1. Where ‘n’ is the size of array.
CSE/C++/Module-I/Trilochan Rout/Lecture: 4, 5, 6 10

➢ References:
- Reference data types are declared with the help of ‘&’ operator.
- It is also called as address of operator.
- C++ reference type declares alias(alternative name) for object variables and allow
the programmers to use the variable by reference.
- It represents that both the variables points to the same memory space.
- So any operation performed on one, will reflect on the other.
- By declaring “&variable-name” we are assigning the address of variable which was
already allocated for the variable.

Example:
#include <iostream.h>
#include <conio.h>
int main()
{
int x=7;
clrscr();
int&y=x; /*y is the reference variable */
cout<<"\n Address of X: "<<&x<<endl<<" Address of Y: "<<&y;
cout<<"\n X = "<<x<<"\tY = "<<y;
x=111;
cout<<"\n New value of X: "<<x <<"\tand"<<"\t Y: "<<y;
getch();
return 0;
}
Output:

Explanation: Here‘y’ is the reference variable of ‘x’. Hence address of both x and
y is same. So any operation performed on x and y will reflect on the other.

• User-defined data type:


- The derived data types which are used in C++ programming are:
1. Structure
2. Unions
3. Class
4. Enumerated
5. Type def
1. Structure:
struct book //declaring a structure
{
char name[20];
int pages;
float price;
};
book b1,b2,b3; //declaring variables of structure type
CSE/C++/Module-I/Trilochan Rout/Lecture: 4, 5, 6 11

- In C++, we do not need the keywords structwhile defining the variables b1, b2, b3.
The main aim behind this is to make the syntax and the operation of the user-
defined datatypes similar to that of built-in datatypes. We can access the variables
of the structure using the dot(.) operator.
Note: By default the structure member are public.

2. Unions:
union data
{
charch[2];
int i;
};
data d;

- Structures and Unions both are used to group a number of different variables
together. But while a structure enables us to treat number of different variables at
different places in memory, a union enables us to treat the same space in memory
as a no. of different variables.
Anonymous unions:
- Unions can also be declared with no type name or object name. In this case, they
become anonymous unions, and its members are directly accessible by their
member names. For example, look at the differences between these two structure
declarations:
structure with regular union structure with anonymous union
struct { struct {
char title[50]; char title[50];
char author[50]; char author[50];
union { union {
float dollars; float dollars;
int yen; int yen;
} price; };
} book; } book;

- The only difference between the two pieces of code is that in the first one, the
union has a name (price), while in the second it has not. This affects the way to
access membersdollars and yen of an object of this type. For an object of the first
type (a regular union), it would be:
▪ book.price.dollars
▪ book.price.yen

whereas for an object of the second type (an anonymous union), it would be

• book.dollars
• book.yen
- Again, remember that because it is a union (not a structure), the membersdollars and yen
actually share the same memory location, so they cannot be used to store two different
values simultaneously. The price can be set in dollars or in yens, but not in both
simultaneously.
-
CSE/C++/Module-I/Trilochan Rout/Lecture: 4, 5, 6 12

3. Class:
- It works same as the structure.
- A class is an abstract data type formed by grouping of object having identical
properties, common behavior and shared relationship.
Syntax:

class<class_name>
{
<member variable list>;
<member function list>;
};
Example:
class student
{
introllno; //data member
intregd_no; //data member
charsname[10];
int input(); //member function
void output(); //member function
};
Note: By default, the class data members and member function are private.
Class structure
Classmembers are by Structure members are by
defaultprivate. default public.
It is a logical concept. It is a physical concept.

It provides bottom to top It provides top to bottom


approach execution. approach execution.

4. Enumerated:
- In enumerated data-types, the values for the variables are already declared and so
there is a choice for selecting the value of the variable only from the declaration.
- It provides a way to attach names to numbers.
- It is useful for creating symbolic constants.
- The programmer can declare new datatype and define variables of these data
types using the keyword enum.
Syntax:
enum<datatype / tag name> { variable lists };
Example-1:
enum logical {false, true};
Explanation: Here the two variables false and true are automatically assigned
constant unsigned integer values starting from 0.
That is here false = 0, true = 1.

Example-2:
enum day{Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday};
day d;
CSE/C++/Module-I/Trilochan Rout/Lecture: 4, 5, 6 13

5. TypedefDatatype:
- Typedef allow the programmer to create an alias for a data type, and use the
aliased name instead of the actual type name. To declare a typedef, simply use the
typedef keyword, followed by the type to alias, followed by the alias name:

typedeflongmiles; // define miles as an alias for long


// The following two statements are equivalent:
longnDistance;
milesnDistance;

- A typedef does not define new type, but is just another name for an existing type.
- A typedef can be used anywhere a regular type can be used.

X. TYPECASTING:
- Converting a variable from one data type to another is called type casting.
- It is basically two types:
▪ Implicit typecasting
▪ Explicit typecasting
➢ Implicit typecasting:
➢ When the compilers carries out the conversion itself by using inbuilt
datatypes in routines then it is called implicit type conversion.
➢ The variable of lower datatypes when converted to higher datatype is
known as demotion.
➢ Explicit typecasting:
➢ When the datatype of a variable is converted forcefully by writing codes, it
is called explicit typecasting.
Syntax:
datatype(expression);
Or
(datatype) variable ;
Example:

Implicit typecasting Explicit typecasting

int a=5,b=2; int a=5,b=2;


float d; float d;
d= a/b; d= float(a/b);
cout<<”d=”<<d; cout<<”d=”<<d;
Output:2.000000 Output:2.5

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy