Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

CP - Unit 1 - 2

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 43

Introduction to C++

Programming
Brief Facts About C++

• Evolved from C
• Designed and implemented by Bjarne Stroustrup at the Bell
Labs in the early 1980s
• “C with classes”
• Standardized by ISO in 1997
– Includes the C++ standard library
– Standard Template Library (STL)
• Part of the C++ standard library
• Readymade classes for data structures and algorithms
Filenames

• Can be different from the name of the class or the name of the function
in the file
• .cpp
– Extension for the C++ source code files
• .h
– Extension for C++ header files
– Usually, code for a data structure is put in a header file, and then it can be
added to a program with an include directive, e.g. #include
"BasicVector.h"
• Name of executable file
– In MSVS it’s the name of your project
– In g++ it’s either “a.out” or a name you specify
Simple C++ Example
/*
FILE: main.cpp
*/
#include <iostream>
#include <string>
using namespace std;

int main() {
cout << "Enter your first name: ";
string name;
cin >> name;
cout << "Hello, " << name << endl;
return 0; //optional
}
Simple C++ Example
/*
FILE: main.cpp
*/
#include <iostream> Comment
#include <string>
using namespace std;
C++ header files from
int main() { C++ standard library
cout << "Enter your first name: ";
string name; Namespace for
cin >> name; C++ standard library
cout << "Hello, " << name << endl;
return 0; //optional
} “Entry” function

All C++ statements


end with a semicolon
The main() function

• The entry point for your program


– Only one main function
– Located outside of any class
– Located in a .cpp source code file
• Return statement inside main()
– return 0; //Successful execution
– Optional
• Two ways to write the signature
int main()
int main( int argc, char *argv[] )
Using Command Line Arguments

Number of items Array of C-style strings


on the command line on the command line
• Program code
int main( int argc, char *argv[] ){
if( argc>1 ){
cout << "Data file is " << argv[1];
}
}
• Open a console window and navigate to the directory where
the executable is, then type the name of the executable
followed by any argument that must be passed to the
program.
c:\> demo.exe "Data.txt"
Output and Input

• cout
– #include <iostream>
– using namespace std;
– operator <<
– Represents standard output, usually the screen
cout << "Enter your first name: ";
• cin
– <iostream>
– operator >>
– Reads keyboard input until the first whitespace
string name;
cin >> name;
• endl
– Used to output a newline and flush output buffer
cout << "Hello, " << name << endl;
Variables and Data Types

Some of the standard C++ data types


bool int float
char short double
unsigned char long

Declaring a variable
– Allocates storage space in memory
– Not automatically initialized
int i; //i is declared but not initialized
int j = 0; //j is declared and initialized
int k(5); //k is declared and initialized

memory address value variable name


3000 i
3004 0 j
3008 5 k
3012
Operators and Expressions

 Binary arithmetic operators


+ addition
- subtraction
* multiplication
/ division
% modulo (finds the remainder)
• An expression — combining variables and literals with operators to
create a new value
Example:
double x, y = 10.0;
x = y / 4.0;

variables operators literal


Integer Division

• The remainder is treated differently


• Division operator
int m, n = 11;
m = n / 5;
cout << "m = " << m; //What prints?

• Modulo operator
int m, n = 11;
m = n % 5;
cout << "m = " << m; //What prints?
Assignment Operator

• Assignment
int n = 10;

assignment operator

• Binary arithmetic operators can be combined with


assignment
n += 5; //same as n = n + 5
n *= 2; //same as n = n * 2
cout << "n = " << n; //What prints?
Equality Operators and
Relational Operators

• Equality operators
– equality operator == (don’t confuse with = )
x == y; //x is equal to y
– operator !=
x != y; //x is not equal to y
• Relational operators
– operator <
x < y; //x is less than y
– operator >
x > y; //x is greater than y
– operator <=
x <= y; //x is less than or equal to y
– operator >=
x >= y; //x is greater than or equal to y
Increment and Decrement

• Post-increment operator
int n = 10;
n++; //returns n then adds 1 to it
• Pre-increment operator
int n = 10;
++n; //adds 1 to n then returns it
• Post-decrement operator
int n = 10;
n--; //returns n then subtracts 1 from it
• Pre-decrement operator
int n = 10;
--n; //subtracts 1 from n then returns it
Variables and I/O

• Values for the fundamental types can be input from the keyboard using
cin and output to the screen with cout

double x;
cout << "Enter a double: ";
cin >> x;
int n;
cout << "Enter an integer: ";
cin >> n;
char c;
cout << "Enter a char: ";
cin >> c;
cout << "double = " << x << " int = " << n;
Constants

• Use const to declare a constant


• Must be initialized with a value when it is
declared
• The name of a constant is usually all caps
const double PI = 3.14159;
const int CAPACITY = 1024;
Conditional Control Structures

• Select from different actions, depending


on whether a condition is true
if( courseScore >= 91 )
courseGrade = "A";
else if( courseScore >= 89 )
courseGrade = "A-";
else
courseGrade = "B";
switch Structure

• Can replace a complicated if/else structure


This controlling expression is
char grade; compared to each of the case labels
cin >> grade;
switch( grade ){ Execution continues at the case label
case 'A': case 'a':
that matches
aCount++;
break; The break causes execution to go to
case 'B': case 'b':
bCount++; the next line following the switch
break;
default:
cout << "Incorrect input" << endl;
break;
}
Iterative Control Structure

• Looping with for Condition – tested at


Initialization – assigns the beginning of
the starting value and each loop, and the Expression –
is executed once. loop is executed only evaluated at the
if it evaluates to true. end of each loop

for( int i=0; i<10; ++i )


Block of {
statements
executed in cout << i << " ";
the loop }
for Loop

for( int i=0; i<10; ++i )


{
A block is needed only if
multiple statements are
cout << i;
executed in each loop. cout << " ";
}
If only one statement is
executed in each loop, it’s for( int i=0; i<10; +
not necessary to define a +i )
block with { and }.
cout << i << " ";
Changes to the Value of i

for( int i=0; i<5; ++i )


{
cout << i << " ";
}
Value of i Expression at the end
Iteration during the loop of the loop
First loop 0 (starting value) i=i+1
Second loop 1 i=i+1
Third loop 2 i=i+1
Fourth loop 3 i=i+1
Fifth loop 4 i=i+1
Nested for Loop

i j result
0 0 1
int result = 0; 0 1 2
for( int i=0; i<3; ++i ) 0 2 3
for( int j=0; j<5; ++j 0 3 4
) 0 4 5
result++; 1 0 6
1 1 7
1 2 8
1 3 9
1 4 10
2 0 11
2 1 12
2 2 13
2 3 14
2 4 15
Nested Loop with Dependent Variable

i j result
0 0 1
int result = 0;
0 1 2
for( int i=0; i<3; ++i )
0 2 3
for( int j=i; j<5; ++j
0 3 4
)
0 4 5
result++;
1 1 6
1 2 7
1 3 8
1 4 9
2 2 10
2 3 11
2 4 12
How many iterations?

for( int i=0; i<10; ++i )


cout << i << " ";

for( int i=10; i>0; --i )


cout << i << " ";

int result = 0;
for( int i=0; i<2; ++i )
for( int j=0; j<3; ++j )
result++;
Looping with while

// C program to illustrate while loop


#include <stdio.h>

int main()
{
// initialization expression
int i = 1;

// test expression
while (i < 6)
{
printf( "Hello World\n");

// update expression
i++;
}

return 0;
}
Looping with Do while

// C program to illustrate do-while loop


#include <stdio.h>

int main()
{
int i = 2; // Initialization expression

do
{
// loop body
printf( "Hello World\n");

// update expression
i++;

} while (i < 1); // test expression

return 0;
}
Array

• Collection of elements of the same data type that are stored in adjacent
memory locations
• Creating an array
int myArray[5];//created but not initialized
• The first element in every array has the index 0
• Each element can be accessed by using its index
myArray[0] = 42;
cout << myArray[0];//what prints?
cout << myArray[3];//what prints?
• Initializing the array
for( int i=0; i<5; ++i )
myArray[i] = 0;
int nextArray[] = {0,0,0,0,0};//created + initialized
Using Arrays

• Use a constant int to declare an array


const int CAPACITY = 5; //Easier to modify
int newArray[CAPACITY];
for( int i=0; i<CAPACITY; ++i )
newArray[i] = 0;

• There is no bounds checking for arrays


cout << myArray[256];//will probably compile!

• Common error
int myArray[5] = {0,0,0,0,0};
cout << myArray[5];
Class string

• C++ uses an object-oriented approach to strings


#include <string>
using std::string;
• Creating a string object
string s1;
string s2("Go Dog");
string s3 = "Madam, I'm Adam";
• Accessing individual chars
s2[5] = 'n'; //What changes?
int len = s2.length(); //returns 6
Some string Operations

• Concatenation with operator +


string s1 = "Hello";
string s2 = "World";
string s3 = s1 + s2 + '!';
cout << s3; //What prints?

• C++ strings can be compared with ==, !=, <, >, <=, and
>=
string s1 = "Hello", s2 = "World";
if( s1 == s2 ) cout << "equal";
Functions and
Argument Passing
Functions

• A small “subprogram” that does a specific task


• A complicated C++ program can be divided into smaller,
manageable pieces by using functions
• Values are passed to a function as arguments
• When the function is finished, it can return a value to the
caller
• We can use functions from the standard C++ library or we
can write our own functions
Function Arguments

• The variables that are used to pass data into a function


or to return results arguments or parameters
function
name
• Example
return bool isPalindrome( string forw, string rev ){
type if( forw == rev )
return true;
}
• Arguments can be passed
– By value – the default in C++
– By reference
Passing Arguments by Value

• Used to pass data only into a function


• When a variable is passed by value, a copy of it is made inside the function. The
copy is destroyed when the function returns.
• Example: passing an argument by value
void noChange( int n ){
n = n + n;
}
int main() {
int num = 5;
noChange( num );
cout << num << endl; //prints 5
}
Reference Argument
• Syntax
int &n
• Indicates that an alias for the argument is
used inside the function
Passing Arguments by Reference

• Used to pass data into and out of a function


• When a variable is passed by reference, no copy is made. Changes to the
reference are passed to the calling variable.
• Example: passing an argument by reference
void change( int &n ){//n is a reference
n = n + n;
}
int main() {
int num = 5;
change( num );//OK to pass regular var
cout << num << endl;//prints 10
}
Using References

• Used primarily for function arguments to


implement “passing by reference”
• Advantage: Efficiency
– No copies of the arguments are made inside the
function
– When data structures are passed as arguments,
this approach is important
C++ Classes and Object

• Class: A class in C++ is the building block, that leads to


Object-Oriented programming. It is a user-defined data
type, which holds its own data members and member
functions, which can be accessed and used by creating an
instance of that class. A C++ class is like a blueprint for an
object.
• A Class is a user defined data-type which has data members
and member functions.
• Data members are the data variables and member
functions are the functions used to manipulate these
variables and together these data members and member
functions defines the properties and behavior of the
objects in a Class
• An Object is an instance of a Class. When a class
is defined, no memory is allocated but when it is
instantiated (i.e. an object is created) memory is
allocated.
• Syntax:
ClassName ObjectName;

• A class is defined in C++ using keyword class


followed by the name of class. The body of class
is defined inside the curly brackets and
terminated by a semicolon at the end.
Defining Class and Declaring Objects
Accessing Data Members
// Member Functions()
// C++ program to demonstrate void printname()
{
// accessing of data members
cout << “Nickname is: " <<
nickname;
#include <iostream> }
using namespace std; };
class Nick
int main() {
{
// Access specifier // Declare an object of class Nick
public: Nick obj1;

// accessing data member


// Data Members
obj1.nickname = "Abhi";
string nickname;
// accessing member function
obj1.printname();
return 0;
}

You might also like