Unit 1
Unit 1
ENGINEERING
Department of Computer Engineering
#include <iostream>
using namespace std;
int main()
{
cout<<“Hello World”;
return 0;
}
Simple C++ program
• <iostream>
– This header supports C++ I/O operations.
– processor directive #include<iostream>
– The standard output stream normally flows to the screen
– The standard input stream normally flows to the keyboard
• main() :
– Entry point of a program.
– Execution of the code starts from this function.
Simple C++ program
• cout
– An object
– Predefined in C++ to correspond with the “standard output stream”
– cin object used for taking input.
– Private Member:
• Members declared in private section
• Can be accessible within class only
– Public Member:
• Members declared in public section
• Can be accessible within the class and outside of class
Member functions in class
1. Inside class definition
class person
{
public:
string name;
int age;
void display()
{
cout<<age<<display;
}
};
Member functions in class
2. Outside class definition
class area
{
public:
float calculate(float l, float w);
};
float area::calculate(float l, float w)
{
float a;
a=l*w;
return a;
}
Access Specifiers
• Example:
int a;
float b,c;
Rules for Naming variables in C++
• The first character of a variable must be a letter or an
underscore.
• The variable name cannot start with a digit.
• It should contain only letters, digits, underscores.
• There is no limit for the length of variable names.
• Declared/Predefined keywords cannot be used as a variable
name.
• Upper and lower case letters are distinct. (Case Sensitive )
Data Types
Data Type Size
Structure
• It is a user defined data type.
• It can store collection of data with similar or non-
similar data types.
• Example:
enum week{Sun,Mon,Tues,Wed,Thu,Fri,Sat};
enum season
{
spring = 0,
summer = 4,
autumn = 8,
winter = 12
};
Enumerations
#include <iostream>
using namespace std;
enum season {spring = 0, summer = 4, autumn = 8, winter = 12 };
int main()
{
season s1;
s1=winter;
cout << “Value for s1 winter = “<< << endl;
return 0;
}
Contol Structures
Control Structures are just a way to specify flow
of control in programs.
• Decision/Selection statements
• Iteration Statements (Loops)
• Jump Statements
1. Decision/Selection Structures
Used to make decision in a program
1. if statement
2. if – else
3. if – else – if (if-else ladder)
4. nested if
5. switch case statement
if statement
Syntax:
if (condition) {
// block of code to be executed if the
condition is true
}
Example:
if (a>b)
{ cout<<“a is greater”; }
if else statement
Syntax: Example
if (condition) if (a>b)
{ {
// block of code cout<<a;
} }
else else
{ {
// block of code cout<<b;
} }
if else ladder
Syntax: Example
if (condition1) if (a>b)
{ {
// block of code cout<<a;
} }
else if (condition2) else if(a==b)
{ {
// block of code cout<<“equal”;
} }
else else
{ {
// block of code cout<<b;
} }
nested if
Syntax: Example
if (condition1) int a=20,b=10,c=2;
{ if (a>b)
// block of code {
if (condition2) if(a>c)
{ {
// block of code cout<<a;
} }
}
}
switch statement
default: // default_statements;
break;
}
2. iteration statement / loops
• In Programming, sometimes there is a need to perform some
operation more than once or (say) n number of times.
• Loops come into use when we need to repeatedly execute a
block of statements.
}
for loop
• A For loop is a repetition control structure that allows us to
write a loop that is executed a specific number of times.
• firstly initializes, then, condition check, execute body, update
Syntax:
for (initialization expr; test expr; update expr)
{
// body of the loop
// statements we want to execute
}
}
for loop
Example 1: #include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 5; i++)
{
cout << "Hello World\n";
}
return 0;
}
}
for loop
Example 2: #include <iostream>
using namespace std;
int main()
{
int i = 99;
for (int i = 0; i < 5; i++)
{
cout << i << "\t";
}
cout << "\n" << i;
return 0;
}
}
for loop
Example 3: #include <iostream>
using namespace std;
int main()
{
int i = 99;
for ( i = 0; i < 5; i++)
{
cout << i << "\t";
}
cout << "\n" << i;
return 0;
}
}
for loop
Example 4:
#include <iostream>
using namespace std;
int main()
{
for (int i = 0, j = 10; (i + j) < 20; j++, i += 2)
{
cout << i << " " << j << "\n";
}
return 0;
}
}
for loop
Example 5:
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i<5; i++)
{
for(int j=0; j<i; j++)
{
cout << “*” << “\t”;
}
cout<<“\n”;
}
return 0;
}
}
while loop
• While studying for loop we have seen that the number of iterations
is known beforehand, i.e. the number of times the loop body is
needed to be executed is known to us.
• while loops are used in situations where we do not know the exact
number of iterations of the loop beforehand.
• The loop execution is terminated on the basis of the test conditions.
• Syntax:
initialization expression;
while (test_expression)
{
// statements
update_expression;
}
}
while loop
Example: #include <iostream>
using namespace std;
int main()
{
int i = 1; // initialization expression
while (i < 6) // test expression
{
cout << "Hello World\n";
i++; // update expression
}
return 0;
}
do while loop
• In the do-while loop, the condition is tested at the end of the
loop body, i.e do-while loop is exit controlled.
• The loop body will execute at least once irrespective of the
test condition.
• Syntax:
initialization expression;
do
{
// statements
update_expression;
} while (test_expression);
do while loop
Example: #include <iostream>
using namespace std;
int main()
{
int i = 2;
do {
cout << "Hello World\n";
i++;
} while (i < 1);
return 0;
}
3. jump statements
• Syntax:
arr[i] = new_value;
• Example:
a[3] = 40;
Traverse an Array
#include <iostream>
using namespace std;
int main()
{
int two[10] = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
for (int i = 0; i < 10; i++)
{
cout << two[i] << " ";
}
return 0;
}
Strings
• Text written in double quotes is called as string.
• At the end of string one special character is
appended automatically called null character.
• Null character = ‘\0’
• String is nothing but an array of character.
• We use char array to store and process string values
in programs.
Strings
• Syntax:
char name_variable[size];
• Example:
char a[20];
• Input a String:
cin>>a; //inputs a word
cin.getline(a,20);
• Output a string:
cout<<a;
String Manipulation functions
• Include <string.h> header file
1. strlen(char [])
2. strcmp(char [], char [])
3. stricmp(char [], char [])
4. strcat(char [], char [])
5. strncat(char [], char [], n)
6. strcpy(char [], char [])
7. strncpy(char [],char [] ,n)
Functions
• A function is a set of statements that takes input,
does some specific computation, and produces
output.
• A function runs only when it is called.
• Syntax:
return_type function_name(parameter list)
{
body of function
}
Functions
• Example:
2. Pass by Reference:
– Both actual and formal parameters refer to the same locations,
so any changes made inside the function are reflected in the
actual parameters of the caller.
Default values for parameters
• While defining a function, we can
specify default value for last Example:
parameters.
• This value is used if corresponding int sum(int a, int b = 20)
argument is left blank while {
calling. int result = a + b;
return result;
• Once a default value is used for an
}
argument in the function definition,
all subsequent arguments to it must
have a default value as well.
Constructor
• Constructor is special member function of a class that is
executed whenever we create an object of that class.
• Very useful for setting initial values for member
variables.
• Constructor has same name as the class.
• They do not return values; hence they do not have a
return type.
• They are automatically called when objects are created.
Types of Constructor
1. Default constructor
2. Parameterized constructor
3. Copy constructor
1. Default Constructor
• Default constructor is the constructor which
doesn’t take any argument.
• It has no parameters.
• It is also called a zero-argument constructor.
2. Parameterized Constructor
• It is possible to pass arguments to constructors.
• To create a parameterized constructor, simply add
parameters to it the way you would to any other
function.
• When you define the constructor’s body, use the
parameters to initialize the object.
3. Copy Constructor
• A copy constructor is a member function that
initializes an object using another object of the
same class.
Destructor
• A destructor is also a special member function like
a constructor.
• Destructor destroys the class objects created by
the constructor.
• Destructor has the same name as their class name
preceded by a tilde (~) symbol.
• There can be only one destructor in a class.
• Destructor neither requires any argument nor
returns any value.
Destructor
• Destructor release memory space occupied by the
objects created by the constructor.
• It is automatically called when an object goes out
of scope i.e. when function or program ends.
Objects and memory
requirements
• Memory Allocation : reserving memory for
variables, arrays, objects, etc.
• When we create variables or objects, memory is
allocated to them.
• Types:
1. Static memory allocation
2. Dynamic memory allocation
Objects and memory
requirements
Static Memory Allocation
• Allocating fixed amount of memory for data at
starting of the program or function.
• Drawbacks:
– Allocated memory can be larger, resulting in wastage
of memory
– Allocated memory can be lesser, resulting in program
failure.
Objects and memory
requirements
Dynamic Memory Allocation
• Size of memory is decided according to
program/user requirements.
• Memory can be allocated or de-allocated at any
stage of program.
• Dynamic memory allocation uses pointers.
• Keyword new is used to allocate a memory and
delete to free a memory.
new
• Allocating memory to one variable/object:
pointer-variable = new data-type;
Syntax:
• for a global function: